Add a city field and state field to a table of zip codes with Python

10-22-2020 04:09 PM
New Contributor

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? 

Tags (2)
0 Kudos
4 Replies
MVP Esteemed Contributor

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

... sort of retired...
0 Kudos
New Contributor

I was thinking of creating a separate csv file and creating a list of zip codes/cities/states manually. 

0 Kudos
Esri Contributor
Esri Contributor

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:

  1. cityFC = r"C:\data\city_polygons.shp"  

  2. stateFC = r"C:\data\state_polygons.shp"  

  3. arcpy.MakeFeatureLayer_management(infeatures, "index_fl")  

  4. searchRows = arcpy.da.SearchCursor(cityFC, ["SHAPE@","CITY_NAME"])  

  5. for searchRow in searchRows:  

  6.    geomObj, cityName = searchRow  

  7.    arcpy.SelectLayerByLocation_management("index_fl", "INTERSECT", geomObj, "", "NEW_SELECTION")  

  8.    arcpy.CalculateField_management(infeatures, "city", "'" + cityName + "'", "PYTHON", "")  

  9. searchRows = arcpy.da.SearchCursor(stateFC, ["SHAPE@","STATE_NAME"])  

  10. for searchRow in searchRows:  

  11.    geomObj, stateName = searchRow  

  12.    arcpy.SelectLayerByLocation_management("index_fl", "INTERSECT", geomObj, "", "NEW_SELECTION")  

  13.    arcpy.CalculateField_management(infeatures, "city", "'" + stateName + "'", "PYTHON", "")