[GIS] How to convert Zipcode+4 into standard 5 digit zip code using Field Calculator

attribute-tablefield-calculatorpython

I have a ZCTA shapefile that I would like to join to a table by the zipcode. My problem is that some of the zip codes in the table have a 5+4 digit format, and the ZCTA shapefile has only the 5 digit format. I would like to remove the last 4 digits of the 9 digit zipcodes using field calculator. My current method was to use slicing in python, but the code will not run. This is what im currently using: I created a new field in the table ('Field9') of type text and made it equal to the zipcode field 'ZIP' and used field calculator with this code

Field9=
!ZIP!

for i in Field9:
    if len(i)>5:
        i = i[0:4]

Why wont this compile? I am fairly new to using python on arc.

Best Answer

Assuming your field ZIP is in string format (which means that even zip codes in the eastern US will have either 5 or 9 digit zip codes), simply enter !ZIP![:4] in the Field Calculator, making sure the parser is Python. This will grab the first 5 characters, whether it is a 5 digit or 9 digit zip code, and whether it has a dash or not separating the zip+4.

Loops are not needed in the Field Calculator as these are processed row-by-row.

If the ZIP field is numeric, you will first need to convert the value to string with zero-padding. Since the lengths vary, it would be best to use a function definition in the codeblock, then call the function.

Here's a resource explaining how to set up code blocks for the Field Calculator in ArcGIS Pro: http://pro.arcgis.com/en/pro-app/tool-reference/data-management/calculate-field-examples.htm. The process is similar in ArcGIS Desktop 10.x but you will need to ensure you select the Python parser.