I'm trying to update missing values in one .shp from another .shp. I'm using SelectLayerByLocation to identify the properties which lie within the boundaries of a suburb and then using a UpdateCursor to update the properties list with the suburbs. The code below doesn't iterate through the list correctly so all I get is the first value from the initial SearchCursor updating the properties list.
fc_P = propertyDataset
fc_S = suburbsDataset
LOCALITYList = []
query = '"LOCALITY" =\'\''
field_P = ["LOCALITY"]
field_S = ["ADMINAREA"]
arcpy.MakeFeatureLayer_management(fc_S,"Suburbs_layer")
arcpy.MakeFeatureLayer_management(fc_P,"Properties_layer", query)
arcpy.SelectLayerByLocation_management("Properties_Layer", "WITHIN",
"Suburbs_Layer")
with arcpy.da.SearchCursor("Suburbs_layer",field_S) as Srow:
for row in Srow:
Suburb = Srow[0]
with arcpy.da.UpdateCursor("Properties_layer", field_P) as Ucursor:
for Urow in Ucursor:
Urow[0] = Suburb
Ucursor.updateRow(Urow)
del Ucursor
del Srow
1 Answer 1
I think you should try using spatial join instead. That way you dont need to iterate Select Layer By Location and multiple cursors. The output can be written to in_memory so that it not saved to disk and the output is used to create a dictionary of objectids and their suburb.
Try code below, I have no data to try it on so you might get some errors:
import arcpy
propfc = 'Properties'
subfc = 'Suburbs'
propfc_suburbfield = 'LOCALITY'
subfc_suburbfield = 'ADMINAREA'
#Create feature layer of properties with LOCALITY shorter than 2 charachters
sql = "CHAR_LENGTH({0})<2".format(arcpy.AddFieldDelimiters(propfc, propfc_suburbfield))
arcpy.MakeFeatureLayer_management(in_features=propfc, out_layer='proplyr', where_clause=sql)
#Spatial join suburbs to properties layer
tempspatjoin = r'in_memory\spatjoin'
arcpy.SpatialJoin_analysis(target_features='proplyr', join_features=subfc, out_feature_class=tempspatjoin, join_type='KEEP_COMMON',\
match_option='WITHIN')
#Create a dictionary of property objectids and what suburb they are in
updatedictionary = {k:v for k,v in arcpy.da.SearchCursor(tempspatjoin,['TARGET_FID',subfc_suburbfield])}
#Update proplyr with suburbs from dictionary
with arcpy.da.UpdateCursor('proplyr',['OID@',propfc_suburbfield]) as cursor:
for row in cursor:
if row[0] in updatedictionary: #If this rows oid is in dictionary
row[1] = updatedictionary[row[0]] #Update with suburb
cursor.updateRow(row)
for locality in localitylist:
)