Select to view content in your preferred language

Count number of features inside polygon

2569
12
Jump to solution
03-19-2020 01:30 PM
CCWeedcontrol
Regular Contributor

I need some help on my code to count the number of features inside a polygon. I have the following but after testing it, it doesn't seem to be correct. I am trying to figure out how many parcel lots are within the subdivision boundary. My test show after running the code that the "Stats" table has 9 Frequencies but in actually there is 10 parcels within the subdivision. I have tried "HAVE_THEIR_CENTER_IN" but all the results are 1.

import arcpy, os

mxd = arcpy.mapping.MapDocument("current")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
lyr = arcpy.mapping.ListLayers(mxd, "Taxlots")[0]
subs = arcpy.mapping.ListLayers(mxd, "SubsOutsideCities")[0]
#arcpy.MakeFeatureLayer_management(par, "parLyr")

arcpy.SpatialJoin_analysis(subs, lyr,"in_memory/points_SpatialJoin", "JOIN_ONE_TO_MANY", "KEEP_ALL", "", "CONTAINS")
arcpy.Statistics_analysis("points_SpatialJoin", "in_memory/stats", "Join_Count COUNT","OBJECTID")
‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
12 Replies
CCWeedcontrol
Regular Contributor

If i run the following in stand alone python, every value in VxCount1 has the same number.

subs = r'C:\Temp\SubsOutsideCities_Temp.shp'
lyr = r'C:\Temp\TaxParcels.shp'

with arcpy.da.UpdateCursor(subs, ["VxCount1", "Shape@"]) as cursor: # cycle through outer polygon layer
    for row in cursor:
        arcpy.management.SelectLayerByLocation(lyr, "HAVE_THEIR_CENTER_IN", row[1]) # row[1] is SHAPE@
        row[0] = int(arcpy.GetCount_management(lyr)[0]) # row[0] to be updated with count‍‍‍‍‍‍‍
        cursor.updateRow(row) # update row
0 Kudos
RandyBurton
MVP Alum

You may need to use Make Feature Layer to convert your shape file into a "layer".

CCWeedcontrol
Regular Contributor

Got it to work with making a feature layer. and adding row 10

lyr = r'C:\Temp\TaxParcels.shp'
subs = r'C:\Temp\SubsOutsideCities_Temp.shp'
arcpy.MakeFeatureLayer_management(lyr, "parLyr")


with arcpy.da.UpdateCursor(subs, ["VxCount", "Shape@"]) as cursor: # cycle through outer polygon layer
    for row in cursor:
        arcpy.management.SelectLayerByLocation("parLyr", "HAVE_THEIR_CENTER_IN",row[1]) # row[1] is SHAPE@
        count = int(arcpy.GetCount_management("parLyr")[0])# row[0] to be updated with count
        row[0] = (count)
        cursor.updateRow(row) # update row