ArcPy Field Calculator – How to Calculate Multiple Fields Using ArcPy

arcpyfield-calculatorreclassify

I am working on adding multiple new fields to a feature and then reclassify the values based on existing fields. Here is a part of the code where it does the reclassification and I am curious if there is a cleaner way to do this considering I have around 15 fields that I want to calculate which means I would have to write 15 codeblocks, expression and a line for CalculateField_management(my assumption). The below code just shows calculation field for 2 fields. I'm rather new to the backside of Python programming, so my current code is slightly cumbersome:

import arcpy
import os, sys

arcpy.env.workspace = r'C:\Project\2022\03\test.gdb'
shapefile = "31Dec2021"

expression_1 = "Reclass(!F_MaxIntCur!)"
expression_2 = "Reclass(!Test!)"

codeblock_1 = """
def Reclass(F_MaxIntCur):
    reclass = {
        1: 1,
        1.5: 1.5,
        2: 2,
        2.5: 10,
        3: 16,
        3.5: 56,
        4: 98,
        4.5: 624,
        5: 1152
    }
    return reclass.get(F_MaxIntCur)
    """
codeblock_2 = """
def Reclass(Test):
    reclass = {
        3: "Murder-Manslaughter",
        4: "Racism",
        5: "Robbery",
        6: "Aggravated Assault",
    }
    return reclass.get(Test)
    """

arcpy.CalculateField_management(shapefile, "CurrentViolIntScore", expression_1, "PYTHON_9.3", 
                                codeblock_1)
arcpy.CalculateField_management(shapefile, "CurrentViolDescription", expression_2, "PYTHON_9.3", 
                                codeblock_2)

Best Answer

Yes, you can significantly reduce your code because update cursor lets you order fields to be updated. So for table like that:

enter image description here

script:

lookups=[{1:'Apple',2:'Orange'},{1:'Dog',2:'Wolf'}]
with arcpy.da.UpdateCursor("FeatureClass",['from_A','to_A','from_B','to_b']) as cursor:
    for row in cursor:
        for i in range(len(lookups)):
            aDict = lookups[i]
            k = row[2*i]
            row[2*i+1] = aDict[k]
        cursor.updateRow(row)

will result in:

enter image description here

Number of fields doesn't matter and your script will work much faster.

Related Question