Thursday, 22 December 2016

arcgis 10.1 - Using Select By Location to update field in feature class using ArcPy?


I am using Arc 10.1 and I am working on a script that takes a value from a field within one shape file and updates a field in another shape file based on its location. Basically I have smaller parcels that reside within larger areas and I want to assign the name of the larger area to a field within the smaller parcels.


The issue I am having is that when I run the script, every parcel ends up having the same "area". I believe its because its essentially writing each area to the parcel and then rewriting it again and again until there are no more areas to loop through. Can someone provide some advice?


#Make a feature layer for the neighourhoods
arcpy.MakeFeatureLayer_management(neighbourhood, "neighbourhoodLayer")
arcpy.MakeFeatureLayer_management(parcel, "parcelLayerTest1")

#Setup cursor to update new NBHD field
with arcpy.da.UpdateCursor(parcel, (parcelIDField,nbhdField)) as parRows:
for par in parRows:
# Create a query string for the current patrol zone
#parcelIDstring = par[0]
#queryString = '"' + str(parcelIDField) + '" =' + "'" + str(parcelIDstring) + "'"

#Select parcels based on location contained within neighbourhood
arcpy.SelectLayerByLocation_management("parcelLayerTest1", "HAVE_THEIR_CENTER_IN", neighbourhood)


nbhdTable = arcpy.SearchCursor(neighbourhood)
for nbhd in nbhdTable:
nbhdValue = nbhd.getValue("Neighbourh")
if nbhdValue:
par[1] = nbhdValue
parRows.updateRow(par)

Answer



The problem with your code lies in the logical flow and that you are selecting all the parcel features each time your arcpy.SelectLayerByLocation_management is called. You should re-work your code flow to:



  1. First cursor/select each neighborhood feature (within cursor use select by attribute)


  2. Select by location using neighbohood selected features to select parcel features

  3. Perform update cursor on selected parcel features or use Calculate Field tool to perform the value update grabbed from step 1 value


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...