Retrieving Total Counts

In ArcGIS, the Summary Statistics tool is typically used to calculate a total count of unique occurrences in one field by a case field.
This is a table generated by the Summary Statistics tool showing the number of zip codes per state.

However, when you need this information in Python, you can avoid using the Summary Statistics tool and a search cursor. Instead, you can use the Counter class in the collections module. This will create a dictionary of keys and their counts. Here is the Python code and sample of the resulting dictionary:

Python code:

import collections
import arcpy

zipcode_cnt = collections.Counter(row[0] for row in arcpy.da.SearchCursor("ZipCodeBoundaries", "STATE"))

Result:

Counter({u’TX’: 1760, u’CA’: 1702, u’NY’: 1599, u’PA’: 1487, u’IL’: 1278, u’OH’: 1011, u’MO’: 984, u’FL’: 950, u’MI’: 908, u’IA’: 889, u’MN’: 862, u’VA’: 849, u’NC’: 741, u’WI’: 723, u’KY’: 719, u’GA’: 693, u’IN’: 689, u’KS’: 688, u’TN’: 606, u’AL’: 604, u’OK’: 591, u’WV’: 578, u’AR’: 572, u’NE’: 566, u’NJ’: 554, u’WA’: 536, u’MA’: 497, u’LA’: 478, u’CO’: 461, u’MD’: 435, u’ME’: 419, u’OR’: 400, u’MS’: 387, u’SC’: 382, u’ND’: 374, u’SD’: 352, u’AZ’: 334, u’MT’: 321, u’NM’: 284, u’CT’: 270, u’ID’: 252, u’VT’: 248, u’NH’: 243, u’UT’: 226, u’AK’: 213, u’NV’: 151, u’WY’: 141, u’PR’: 119, u’HI’: 90, u’RI’: 76, u’DE’: 59, u’DC’: 26})

Using a key, you can retrieve a value:

>>> print(zipcode_cnt['CA'])
1702

See the collections module documentation for more information about the Counter class and other useful container datatypes.

3 thoughts on “Retrieving Total Counts

  1. Very concise, I like it. Since Counter is only available with 2.7 (aka 10.1) here is an equivalent using defaultdict which is also from collections that should be fine in 2.6 (aka 10.0 and up) but will be slower because it does not get the full benefit of the new da module.

    import collections
    import arcpy

    zipcode_cnt = collections.defaultdict(int)
    for row in arcpy.SearchCursor(“ZipCodeBoundaries”):
    zipcode_cnt[row.GetValue("STATE")] +=1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s