I have a shapefile of zip codes in the U.S. I am brand new to coding. Using Python, how can I add a city field and state field with the appropriate cities/states for each zip code?
I need to do this with the import arcpy module.
Is this possible?
There is no arcpy method or property that can translate zip codes to what you want. You need to find a data source that contains the conversion and perform a "join" to your existing dataset
I was thinking of creating a separate csv file and creating a list of zip codes/cities/states manually.
this might be useful:
https://community.esri.com/docs/DOC-15525-httpssimplemapscomdataus-zips
If you had the data matching zipcodes to cities and states you would simply perform a join. however if all your data is geospatial (polygons etc..) and you wish to update the fields you could perform the following:
however if you have the cities and states as shapefiles
adding the fields would be done along these lines:
# Import system modules
import arcpy
# Set environment settings
arcpy.env.workspace = "C:/data/"
# Set local variables
inFeatures = "zipcodes.shp"
fieldName1 = "city"
field_length1 = 8
fieldName2 = "state"
fieldLength2 = 10
# Execute AddField twice for two new fields
arcpy.AddField_management(inFeatures, fieldName1, "TEXT",field_length=field_length1)
arcpy.AddField_management(inFeatures, fieldName2, "TEXT", field_length=fieldLength2)
once the fields are added they could be updated using something similar to this:
cityFC = r"C:\data\city_polygons.shp"
stateFC = r"C:\data\state_polygons.shp"
arcpy.MakeFeatureLayer_management(infeatures, "index_fl")
searchRows = arcpy.da.SearchCursor(cityFC, ["SHAPE@","CITY_NAME"])
for searchRow in searchRows:
geomObj, cityName = searchRow
arcpy.SelectLayerByLocation_management("index_fl", "INTERSECT", geomObj, "", "NEW_SELECTION")
arcpy.CalculateField_management(infeatures, "city", "'" + cityName + "'", "PYTHON", "")
searchRows = arcpy.da.SearchCursor(stateFC, ["SHAPE@","STATE_NAME"])
for searchRow in searchRows:
geomObj, stateName = searchRow
arcpy.SelectLayerByLocation_management("index_fl", "INTERSECT", geomObj, "", "NEW_SELECTION")
arcpy.CalculateField_management(infeatures, "city", "'" + stateName + "'", "PYTHON", "")