I am using python to calculate fields with a SQL statement. I need to select based on two attributes and calculate another attribute. The way I am typing it is incorrect syntax.

This is a small portion of the code and will run on a specific feature class.

Here is the code:

codeblock = """def calcFerry(FERRY_TYPE,AR_AUTO):
    if(FERRY_TYPE == 'B') and (AR_AUTO == 'N')
         return 'P'
    elif(FERRY_TYPE == 'B') and (AR_AUTO == 'Y')
         return 'A'"""

arcpy.CalculateField_management(outTemp_file, "FERRY",     calcFerry(!FERRY_TYPE!,!AR_AUTO!)", "PYTHON", codeblock)

There's another way to calculate fields:

    shapefile = "FerryData"
    fields    = ("FERRY_TYPE", "AR_AUTO","CATEGORY")
    with arcpy.da.UpdateCursor(shapefile, fields) as Cursor:
         for row in Cursor:
             if row[0]=='B' and row[1]=='N':
                row[2] = 'P'
             elif row[0]=='B' and row[1]=='Y':
                row[2] = 'A'

The shapefile name ("FerryData"), and the calculated field ("CATEGORY") are just examples. Change them to match yours. This is way faster than CalculateFields in python scripts.

  • Depending on number of records and field index, it can be faster to perform two select layer by attribute and two field calculate. (Or going the cursor route, two separate cursors with where_clauses.) – Paul Feb 24 '17 at 17:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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