Wednesday 3 June 2015

arcpy - Count number of attributes for unique field values in ArcGIS for Desktop?



Running ArcGIS 10.1 for Desktop, I have two feature classes in a geodatabase. One is a point FC for polling stations, the other is a polygon FC for states.



The polling station FC contains over 1000 points and has a states field indicating which state the polling station is located in. The states FC has an attribute for each state and has a blank field for the number of polling stations in each state.


I need a python script that will get the count of how many polling stations are located in each state from the polling station FC, and then write those numbers to the column in the states FC - obviously to their corresponding state.



Answer



If you are using ArcGIS I would think an easy way to do this, without creating any intermediary products, would be to select each state in your states polygon (assuming you have multipart features) and then select by location the polling stations features. You can then get a count of how many features are selected and writing this value to your states polygon. This would look something like this:


import arcpy

# Define some variables
#
polling_stations = r'c:\path\to\geodatabase.gdb\polling_stations'
states = r'c:\path\to\geodatabase.gdb\states'


# Make feature layers for processing
#
polling_stations_lyr = arcpy.MakeFeatureLayer_management(polling_stations,r'in_memory\polling_stations_lyr')
states_lyr = arcpy.MakeFeatureLayer_management(states,r'in_memory\states_lyr')

# Create an update cursor to access and update states features
#
fields = ['field_containing_state_names','field_which_will_be_updated_with_#_of_polls']
with arcpy.da.UpdateCursor(states_lyr,fields) as cur:

for row in cur:

# Make a query to select this feature to be used in a selection of polling places
#
state = row[0]
where = '"field_containing_state_names" = \'{}\''.format(state)
arcpy.SelectLayerByAttribute_management(states_lyr,'NEW_SELECTION',where)

# Now select the polling stations by location using the selected state feature
#

arcpy.SelectLayerByLocation_management(polling_stations_lyr,'INTERSECT',states_lyr)

# Count the number of polling stations selected
#
number_of_polling_stations = int(arcpy.GetCount_management(polling_stations_lyr).getOutput(0))

# Update the state feature with this value
#
row[1] = number_of_polling_stations
cur.updateRow(row)


print('Operation complete.')

This code requires ArcGIS 10.x, but can be made compatible with previous versions by using the older style cursor in place of the data access module cursor used here.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...