0

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.

1
  • 2
    1) Please note that you'll need to create a function definition in the codeblock if you want to use the if statement (and don't need the loops at all in Field Calculator), but if you simply want to grab the first 5 digits, you can simply enter !ZIP![:4] 2) What is the data type of field ZIP? If it's not string you'll need to zero pad it for leading zeroes in the zipcode.
    – SMiller
    Dec 7, 2018 at 17:52

2 Answers 2

2

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.

0

Not sure why it does not like what you're doing. Try a simple slice expression (no code box): !ZIP![0:4] I don't see why you need to test what is in the field, since they all need to be 5 characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.