Select to view content in your preferred language

Calculate field values using arcpy.da.UpdateCursor

5123
11
02-13-2017 06:22 PM
TessOldemeyer
Regular Contributor

I am trying to create and update a field with a count of line features (tLayer) within a distance of point features (sLayer). I am attempting to use a combination of AddField_management, arcpy.da.SearchCursor, SelectLayerByLocation_management, arcpy.GetCount_management, and arcpy.da.UpdateCursor. The code I have for this is currently updating all records for the Line_Count field with the count of the point features (i.e. 2) for only the (second?) record. Though, a print statement following the GetCount line will return the line count for all of the point features (with a few unessential iterations). 

What do I need to do to appropriately update the Line_Count field for all of the records? Also, this process will be applied to a large dataset and will be extended to include 'where clauses'; are there any suggestions as to how to make this as efficient as possible. Any tips or suggestions would be helpful.

Thanks in advance!

Tess

Updated Line_count Field (inaccurately recording a count of '2' for each record) :

 

actual line count values for records as returned by print statement:

import arcpy
from arcpy import env

arcpy.env.OverwriteOutput = True

defaultGdbPath = 'C:\Topo_Check_Tess_V5.gdb'

sLayer='C:\Topo_Check_Tess_V5.gdb\Stations'
tLayer='C:\Topo_Check_Tess_V5.gdb\Lines'
#ppLayer='C:\Topo_Check_Tess_V5.gdb\Plants'

arcpy.AddField_management(sLayer, "Line_Count", "SHORT", "", "", "", "", "NULLABLE", "NON_REQUIRED", "")

TLineCountField = "Line_Count"


arcpy.MakeFeatureLayer_management(tLayer, "tLayer_lyr")
with arcpy.da.UpdateCursor (sLayer, TLineCountField) as LineCountList:
       for s_row in LineCountList:
             with arcpy.da.SearchCursor(sLayer,["OBJECTID", "SHAPE@"]) as s_list:
                      for station in s_list:
                         arcpy.SelectLayerByLocation_management("tLayer_lyr", 'WITHIN_A_DISTANCE', station[1],.000002, "NEW_SELECTION")
                         result=int(arcpy.GetCount_management("tLayer_lyr").getOutput(0))
                         print result
                         LineCountList.updateRow(s_row)
             del station 
    del s_row
 
print "Done"
0 Kudos
11 Replies
TessOldemeyer
Regular Contributor

This is an awesome resource. Thanks!

0 Kudos
IanMurray
Honored Contributor

Yes it is quite useful, I keep it bookmarked on my work computer and GeoNet account.

0 Kudos