How do I count occurrences of unique field values?
@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.
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"])