arcpy – Calculate Fields with Null Values Using arcpy.da.UpdateCursor in ArcGIS for Desktop

arcgis-10.1arcpycursortypeerror

How do you calculate fields with null values? I have multiple fields that may have null values, that aren't being calculated in the third field.

enter image description here

import arcpy
with arcpy.da.UpdateCursor(r"...gdb\test.gdb\test",["A", "B", "C"]) as cursor:
    for row in cursor:
        row[2] = row[0] + row[1]
        cursor.updateRow(row)

The result of that calculation is this error:

Traceback (most recent call last):
  File "C:\Users\Desktop\updatecursor2.py", line 4, in <module>
    row[2] = row[0] + row[1]
TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'

The result of the script are the same results when I try to use the field calculator:

enter image description here

How do you use the data update cursor, or field calculator to calculate the sum of the values in a new field if you have null values?

I'm using ArcGIS 10.1 SP1 for Desktop.

Best Answer

Here's a way to replace all the nulls with zeroes:

import arcpy
with arcpy.da.UpdateCursor(r"...gdb\test.gdb\test",["A", "B", "C"]) as cursor:
    for row in cursor:
        a_value = row[0] if row[0] else 0  # Use 0 when "A" is falsy
        b_value = row[1] if row[1] else 0  # Use 0 when "B" is falsy
        row[2] = a_value + b_value
        cursor.updateRow(row)

Note: this doesn't actually update the null values in the table; it merely replaces them with zeroes during calculations. If you want to replace the nulls with zeroes permanently, you could change the penultimate line to row = [a_value, b_value, a_value + b_value].

Related Question