I have a script that I am using to create and calculate a new field based on the features spatial location. Basically, I have a geodatabase that contains parcels by county in florida, and I am trying to calculate which wind_zone they are in based on their location within a shapefile that contains wind zone polygons. The script runs fine, but the wind zone description values are not transferring over, instead the field is populated with nothing but NULL values.
The code I have so far:
import arcpy
# Set overwrite option
arcpy.env.overwriteOutput = True
# Define your workspace. This should be your database with parcels feature class
arcpy.env.workspace = r"C:\Data\HAAS\parc_join\parcels_1.gdb"
# This can be done once for all iterations
arcpy.MakeFeatureLayer_management(r"C:\Data\HAAS\wind_zones\WZ_merge.shp", "lyr_windZones")
for fc in arcpy.ListFeatureClasses():
# KEEPING ORIGINAL LAYERS (NOT CREATING ADDITIONAL "JOINED" LAYER)
# Create FeatureLayers
arcpy.MakeFeatureLayer_management(fc, "lyr_parcels")
# Add a Windzone description field
arcpy.AddField_management("lyr_parcels", "WZ_Desc1", "SHORT")
# Create a search cursor for the WZs
rows = arcpy.SearchCursor("lyr_windZones")
for row in rows:
# What you'll do is select each WZ one at a time, and then select all the parcels in that WZ and calculate the fields
# NOTE: If you are using not using shapefiles, then you'll have to change the FID in the line below to OBJECTID (or similar)
arcpy.SelectLayerByAttribute_management("lyr_windZones", "NEW_SELECTION", "\"FID\" = " + str(row.getValue("FID")))
arcpy.SelectLayerByLocation_management("lyr_Parcels", "HAVE_THEIR_CENTER_IN", "lyr_windZones", "", "NEW_SELECTION")
arcpy.CalculateField_management("lyr_parcels", "WZ_Desc1", "'{0}'".format(str(row.getValue("DESCRIPT"))), "PYTHON_9.3", "")
print "Finished processing " + fc +str(row.getValue("DESCRIPT"))
print "Script Complete"
1 Answer 1
A simpler solution would be to use Spatial Join. For example:
import arcpy, os
# List the parcel feature classes
arcpy.env.workspace = r"C:\Data\HAAS\parc_join\parcels_1.gdb"
fcs = arcpy.ListFeatureClasses()
# The wind zones feature class
zones = r"C:\Data\HAAS\wind_zones\WZ_merge.shp"
out_ws = r'C:\path\to\your\geodatabase.gdb\out_feature_dataset'
for fc in fcs:
# Define the output feature class
out_feature_class = os.path.join(out_ws, fc + '_spatialjoin')
# Perform the spatial join--you can specify the overlap type here (default in intersect)
arcpy.SpatialJoin_analysis(fc, zones, out_feature_class)
Explore related questions
See similar questions with these tags.