[GIS] Writing Python code block in field calculator

arcgis-desktopfield-calculatorif elsepython-parser

I am a novice in Python as well has having minimal experience with ArcMap. Currently I am using a U.S. Census TIGER file, mapping roads in Harris County, TX. I want to add a new field called SPEED, which will return a speed associated with the MTFCC string (MTFCC is the column which classifies road type. e.g. S1400, S1200, etc.).

I opened my attributes table, added a new field called SPEED, clicked on the Field Calculator of the speed column, and inserted my own Python code. I made sure to click Python (not VB), and have my return value be a number. My code is as follows…

def SpeedCalc(MTFCC):
 if MTFCC == "S1400":
      return 25

 elif MTFCC == "S1200":
      return 45

 elif MTFCC == "S1100":
      return 65

 elif MTFCC == "S1630":
      return 25

 elif MTFCC == "S1730":
      return 15

 else:
      return 9999 

I made sure below where 'SPEED = ' is to have "SpeedCalc(!MTFCC!) written. No errors were thrown, but all my columns were listed as 0. I do not have administrative rights to my working computer or else I would insert my code in to Python first and see what is wrong. As far as I'm aware, my syntax is correct and the statement executes but nothing is done. MTFCC are listed as strings in the properties tab.

Best Answer

I have found that sometimes I need to include a single return rather than in each if/elif/else (I do not know why this is the case, but it has happened enough to now be my go to). Try setting a variable and returning just that variable at the end.

Codeblock:

def SpeedCalc(MTFCC):
    x = 9999
    if MTFCC == "S1400":
        x = 25
    elif MTFCC == "S1200":
        x = 45
    elif MTFCC == "S1100":
        x = 65
    elif MTFCC == "S1630":
        x = 25
    elif MTFCC == "S1730":
        x = 15
    return x

Expression:

SpeedCalc(!MTFCC!)

Alternatively create a python dictionary to store your lookup and return values, and return the values from that.

Codeblock:

def SpeedCalc(MTFCC):
    myDict = {'S1400': 25, 'S1200': 45, 'S1100': 65, 'S1630': 25, 'S1730': 15}
    x = 9999
    if MTFCC in myDict:
        x = myDict[MTFCC]
    return x

Expression:

SpeedCalc(!MTFCC!)

A user tried to edit the answer with the following - I am including this as an additional option, however in my experience some python functions just don't work right in field calculator (as with the single vs multiple return values above). Also I often prefer to have the additional lines, particularly for those new to python, as it's easier to read and understand what is actually happening in the code when learning.

def SpeedCalc(MTFCC):
    myDict = {'S1400': 25, 'S1200': 45, 'S1100': 65, 'S1630': 25, 'S1730': 15}
    return myDict.get(MTFCC, 9999)
Related Question