Populate a value in one feature class from value in another feature class using SearchCursor

07-28-2017 12:26 PM
Occasional Contributor II

I have two feature classes:

   COH_Address (points)

   TAXLOTS_NOAT (polygons)

I am trying to find the best code for using a cursor to run through TAXLOTS_NOAT, grab the value for TLNO, and populate the field TLNO_GIS in the COH_Address feature class the TAXLOTS_NOAT feature class field TLNO.

import arcpy
# Local variables:
COH_Address = "C:\\Users\\mclbr\\Desktop\\AddressTest.gdb\\Places\\COH_Address"
TAXLOTS_NOAT = "C:\\Users\\mclbr\\Desktop\\AddressTest.gdb\\TAXLOTS_NOAT"
arcpy.MakeFeatureLayer_management(TAXLOTS_NOAT, "TAXLOTS_NOAT")  
rows = arcpy.SearchCursor("TAXLOTS_NOAT", "", "", "TLNO", "")
arcpy.MakeFeatureLayer_management(COH_Address, "COH_Address")  
for row in rows:  
    arcpy.SelectLayerByLocation_management("COH_Address", "HAVE_THEIR_CENTER_IN", "TAXLOTS_NOAT", "", "NEW_SELECTION")  
    arcpy.CalculateField_management("COH_Address", "TLNO_GIS", "%(row.TLNO)", "PYTHON")
0 Kudos
1 Reply
Occasional Contributor II

Looks like you're on the right track, however I think its over complicated a little doing a spatial join for each row. Instead you can use Geometry Objects and their spatial operations. It is easier to work with the more modern arcpy.da.SearchCursor and UpdateCursor when you want to access the geometry of your feature classes. Here is an example of using this method:

from arcpy.da import SearchCursor
from arcpy.da import UpdateCursor

COH_ADDRESS = "C:\\Users\\mclbr\\Desktop\\AddressTest.gdb\\Places\\COH_Address"
TAXLOTS_NOAT = "C:\\Users\\mclbr\\Desktop\\AddressTest.gdb\\TAXLOTS_NOAT"

arcpy.AddField_management(COH_ADDRESS, 'TLNO', 'TEXT')

# SHAPE@XY gives us the centroid
coh_fields = ['SHAPE@XY', 'TLNO']
# SHAPE@ gives us the Geometry object
taxlots_fields = ['SHAPE@', 'TLNO']

# using a list allows us to loop over the cursor multiple times
coh_list = [i for i in UpdateCursor(COH_ADDRESS, coh_fields)]
taxlots = SearchCursor(TAXLOTS_NOAT, taxlots_fields)

# for each taxlot
for taxlot in taxlots:
    # Find coh rows with no TLNO and centroids within taxlot
    # [i for i in coh_cursor if not i[1]] is a list comprehension which 
    # returns only coh_list rows with TLNO = None, to reduce the amount of
    # compares per iteration as the values are set.
    for coh_address in [i for i in coh_list if not i[1]]: 
        # if so, update that row with the TLNO from taxlot
        if coh_address[0].within(taxlot[0]):
            coh_address[1] = taxlot[1]
0 Kudos