1

I have seen :

arcpy.Frequency_analysis(inTable, outTable, frequencyFields, summaryFields)

But This creates a new table with the results. I just want to add another field that will do that to an existing feature layer.

Example:

Desired output

For the NTX layer, counts each row how many times occurs in the dataset. if SSA occurs 21 times the new column 'count' will be like this:

NTX
name COUNT
SSA   21
SSC   1
SDD   98
...

In pandas this can be:

df['count_']=[df['col1'].value_counts().loc[x] for x in df['col1']]

How to do it in ArcPy?

  • You should try and make your questions more clear and you will get answers. For example this one, if the feature layer has 21+1+98 rows, you cant add one column with three entries. What is your desired output? – BERA Nov 6 '18 at 13:55
  • I have updated it.I want to make a new column that will count how many times values in the name column appear.The values are not 3 it is supposed to keep on and on. – user51332 Nov 6 '18 at 14:00
  • So each of the 21 SSA rows will have the value 21 in a new column? – BERA Nov 6 '18 at 14:06
  • exactly. that is true – user51332 Nov 6 '18 at 14:07
4

Use collections.Counter:

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Add a field for the counts and then:

from collections import Counter
import arcpy
fc = "my_riks" #Change
countfield = "KKOD" #Change
updatefield = "Count" #Change, field needs to be added Before executing the code

c = Counter([i[0] for i in arcpy.da.SearchCursor(fc,countfield)])

with arcpy.da.UpdateCursor(fc,[countfield,updatefield]) as cursor:
    for row in cursor:
        row[1] = c[row[0]]
        cursor.updateRow(row)

enter image description here

  • RuntimeError: A column was specified that does not exist. Do you know why? – user51332 Nov 6 '18 at 14:27
  • yes this is is the issue.The field must be an existing one?Because only then works. I just typed 'count' in order to make a field named count to put them and it gave error. Can't it take a new? – user51332 Nov 6 '18 at 14:34
  • So I add in the code an empty field like: arcpy.AddField_management("count").Is this correct? – user51332 Nov 6 '18 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.