I would like to use python to calculate a field (short integer) using other fields (short integer) present in the table. In some cases these fields may have NULL values for one or more of the fields. For example, the new field name is 'total' and total is based upon adding field01 + field02 + field03. Some records (rows) have values for field01, field02, and field03, but some rows only have values for field1 and field2, then field3 is NULL.
I have some code that I believe will work, but I must not be implementing it correctly.
#calculate new field 'total' in feature class 'test'
inFeatures='test'
fieldName01='total'
exSummed = "stack(!field01!+!field02!+!field03!)"
codeBlock = "def stack(*args):
return sum(filter(None, args))"
arcpy.CalculateField_management(inFeatures, fieldName01, exSummed, "PYTHON", codeBlock)
Here is the error I receive...
Thanks -al
UPDATE: @Jason was correct, the triple double quote was my problem. I also modified my code based upon a suggestion posted here.
This is my updated code to reflect my solution:
import sys, string, os, arcpy
from arcpy import env
# Set workspace
env.workspace = "Q:/LandTrendr_04/lt_ancillary/landtrendr_file_geodatabase/templates_testing/LandTrendr_PIRO.gdb"
#=========================
#calculate new field 'total' in feature class 'test'
inFeatures='test'
fieldName01='total'
exSummed = "stack(!field01!,!field02!,!field03!)"
codeBlock = """def stack(field01,field02,field03):
itemList = [field01,field02,field03]
myList = [item for item in itemList if (item !=None)]
return sum(myList)"""
arcpy.CalculateField_management(inFeatures, fieldName01, exSummed, "PYTHON", codeBlock)