I have a polygon feature class which contains many (9952) polygons, some of which overlap each other. I have another point feature class with many points (15998) and one of the fields is called route_number.

What I need to do is for every polygon in the polygon feature class, I need to select the points which intersect it. Then with these selected points I need to find the number of unique values for route_number. For example I can do this in ArcGIS Pro by selecting one polygon feature in the attribute table and then running the "Select Layer By Location" tool. It successfully selects just the points which intersect the polygon.

How do I do this in Python using ArcPy?

I have the following code to do a Select by location however it selects every point in the points feature class. I think this is because the select_features is the whole polygon feature class (polygons). I want this to be just one feature within the polygons feature class.

selection = arcpy.SelectLayerByLocation_management(in_layer='point_fc',overlap_type='INTERSECT',select_features='polygon_fc')
num_points = int(arcpy.GetCount_management(selection)[0])

1 Answer 1


There is no need to iterate select by location (which will be slow). One Intersect with polygons and Points will do the job. Points overlapping multiple polygons will be duplicated in the output. Then you can use pandas module to Count unique values in the intersect output:

import pandas as pd
polygon_id_field = 'KOMMUNNAMN'
point_field_to_count_unique = 'KATEGORI'

#Create a pandas dataframe using da.SearchCursor
df = pd.DataFrame.from_records(data=arcpy.da.SearchCursor('bs_inter_ak',[polygon_id_field, point_field_to_count_unique]), columns = [polygon_id_field, point_field_to_count_unique]) #bs_inter_ak is the intersect output
df2 = df.groupby(polygon_id_field)[point_field_to_count_unique].unique()

Enköping                                 [Slott, Kyrka]
Eskilstuna              [Kyrka, Slott, Trafikflygplats]
Strängnäs                                [Kyrka, Slott]
Västerås      [Kyrka, Annan flygplats, Trafikflygplats]
Name: KATEGORI, dtype: object

df2 = df.groupby(polygon_id_field)[point_field_to_count_unique].nunique()

Enköping      2
Eskilstuna    3
Strängnäs     2
Västerås      3
Name: KATEGORI, dtype: int64

df2.to_clipboard() #Paste to excel etc.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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