6

I have a feature class with a field which contains values 1, 2 and 3. I need to write code that reports the total count for each value:

1: 29 features

2: 52 features

3: 57 features

This is my code so far:

print "start"
import arcpy
arcpy.env.overwriteOutput = 1

fc = r"D:\AVI_DAVID\zevel\zevel.gdb\Export_Output_miv_cur"
lst_field = arcpy.ListFields(fc,"USAGE") #usage is the field
for f in lst_field:
    print f.name

Do I need a SearchCursor? Or an UpdateCursor?

  • I KNOW, BUT IT'S CREATE AN OUTPUT TBL, WHICH IS GOOD, BUT I NEED TO PERFORM THE RESULT INSIDE THE CODE THER IS ALSO TOOL CALLED SUMMARIZE.SAME AS Frequency. AVI – avi Mar 10 '15 at 15:47
  • What format exactly do you want the output to be in? Just printed to the console like "start" is? – nmpeterson Mar 10 '15 at 16:49
8

@nmpeterson's answer is a good one. If you don't want to create a table you can get this information as a SearchCursor. You can do it by making use of a dictionary to tally counts:

import arcpy

fc = r"D:\AVI_DAVID\zevel\zevel.gdb\Export_Output_miv_cur"
field = "USAGE"

#Create dictionary to store unique values
CountDi = {}

with arcpy.da.SearchCursor (fc, field) as cursor:
    for row in cursor:
        if not row[0] in CountDi.keys():
            CountDi[row[0]] = 1
        else:
            CountDi[row[0]] += 1

for key in CountDi.keys():
    print str(key) + ":", CountDi[key], "features"

An alternative would be using lists and sets:

import arcpy

fc = r"D:\AVI_DAVID\zevel\zevel.gdb\Export_Output_miv_cur"
field = "USAGE"

Occurances = []
with arcpy.da.SearchCursor (fc, field) as cursor:
    for row in cursor:
        Occurances.append (row[0])

for i in set(Occurances):
    icount = Occurances.count(i)
    print str(i) + ":", icount, "features"

Many ways to skin a python. Note that this makes use of the data analysis search cursor, which requires ArcGIS 10.1 or newer.

7

There is a tool in ArcGIS called "Frequency" (arcpy.Frequency_analysis()) that allows to to count the number of occurrences of each unique value in a specific field (or unique combinations of values in multiple fields). It will create a new table containing the original field name(s) with a row for each unique value/combination, and another "Frequency" field containing the number of rows in the original feature class with that particular value.

In your case, the arcpy call would look like this:

arcpy.Frequency_analysis(fc, PATH_TO_OUTPUT_TABLE, ["USAGE"])
  • 4
    If licensing prevents access to Frequency then Summary Statistics with a case field provides the same functionality at any license level. – PolyGeo Mar 10 '15 at 20:18

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.