[GIS] Calculating multiple fields using ArcPy

arcpyfield-calculator

I have found a script that can add multiple fields to my existing shapefefile. Now, I need to add to my existing script so that it will calculate the new fields that have been added. In most cases, these calculations will derive from existing values in other fields ex. Crdrt1 = [Field1], Crdrt_min1 = [Field2]. I know that I need to use "fields.arcpy.CalculateField_management" but not sure how or where to add to existing script to get it to loop through and calculate.

import arcpy

#Select Geodatabase
arcpy.env.workspace = "C:.. FOLDER\CASINGS_DATA\casings.gdb"
#Select FeatureClass
shapefile = "Casings"

#List of fields to add, all with same type, precision, and scale
#Fields added to attribute table in reverse order
fields = {
    "Crdrt1": "[DES]",
    "Crdrt_min1": "[GRADE]",
    "Testing": "[NAME]"
}
alias = {
    "Crdrt1": "ok",
    "Crdrt_min1": "test"
}

existing_fields = arcpy.Describe(shapefile).fields


for field in fields:
    if not field in existing_fields:
        arcpy.AddField_management(shapefile, field, "TEXT", 0, 0, 50, alias [aliass])
    arcpy.CalculateField_management(shapefile, field, fields[field])

Best Answer

You need to call CalculateField_management for each field you want to calculate. E.g.

arcpy.CalculateField_management(shapefile, "Crdrt1", "[Field1]")
arcpy.CalculateField_management(shapefile, "Crdrt_min1", "[Field2]")

If you want to use a loop, you could create a dictionary that contains the fieldnames and the expressions for each field. The syntax of the expression depends on the type of database and the expression type. See here for details.

fields = {
    "Crdrt1": "[Field1]",
    "Crdrt_min1": "[Field2]"
}

existing_fields = arcpy.Describe(shapefile).fields

for field in fields:
    if not field in existing_fields:
        arcpy.AddField_management(shapefile, field, "TEXT", 0, 0, 250)
    arcpy.CalculateField_management(shapefile, field, fields[field])