hcopeland

Slow Count Points in Polygons Script

Discussion created by hcopeland on Oct 6, 2011
Latest reply on Oct 11, 2011 by csny490
I wrote this script to iterate through a polygon fc and count the number of points in each polygon and put that information in a new field. The script works, but it is REALLY slow. If I use Hawth's Tools to do the same thing, it takes 20-30 minutes. With this script, it was set to take 4 days. Any ideas what I've done wrong--I have a feeling it's related to the search cursor. Should I not be using the select by location/select by attribute ESRI functions? Thanks, Holly

#-------------------------------------------------------------------------------
# Name:       Count Points in Polygon
# Purpose:
#
# Author:      hcopeland
#
# Created:     22/08/2011
# Copyright:   (c) hcopeland 2011
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import arcpy
from arcpy import env

#getcontext().prec = 8

ws = r'D:\Work\Projects\SageGrouseEasementScenarios2011\Data\FinalModelData.gdb'
arcpy.env.workspace = ws

# set overwrite outputs to true
arcpy.env.overwriteOutput = 1

POINT = 'D:\Work\Projects\SageGrouseEasementScenarios2011\Data\Final_Development_Buildouts\Cumulative_buildouts.gdb\Cumulative_Unconstrained'
POLYGON = 'LekParcelFC'

print 'Making Multipart into Single Part....'
#Convert multipart to singlepart
#arcpy.MultipartToSinglepart_management(POLYGON,"LekParcelFCSingle")

# Converts unselectable feature class into a selectable feature layer
arcpy.MakeFeatureLayer_management(POINT,"point")
arcpy.MakeFeatureLayer_management(POLYGON,"polygon")

rows = arcpy.SearchCursor("polygon")

print 'Calculating Points in Polygons...'

# Loop through each row and count the points in each polygon record
try:
    for row in rows:
        # Select each record inside of the polygon feature class
        #expression = "\"OBJECTID\" =" + str(row.OBJECTID) + ' AND "PARCELNB" <> ' + "''"
        expression = "\"OBJECTID\" = " + str(row.OBJECTID) + ""
        print expression
        SelPoly = arcpy.SelectLayerByAttribute_management("polygon", "NEW_SELECTION",expression)

        # Select all the point that are inside of the polygon record
        SelPts = arcpy.SelectLayerByLocation_management("point", "WITHIN", SelPoly, 0, "NEW_SELECTION")

        # Count the points that are in each polygon
        GetCount = arcpy.GetCount_management(SelPts)

        # Calculate the ASSOC_PTS field with the counted points
        arcpy.CalculateField_management("polygon", "CEFeaturesPreventedHigh", GetCount, "VB", "")

except:
    arcpy.GetMessages(2)
    arcpy.AddError("Script Bombed")

print 'Count Points in Polygon Script Finished!'

Outcomes