pythonarcmap

how to set empty value to zero


I have a table "address_layer" set in the code. There I am trying to sum the column "Anzahl". The problem is that where the value is Empty (nothing in it) the code breaks.

polygon_layer = arcpy.GetParameterAsText(0)
address_layer = arcpy.GetParameterAsText(1)

selected_oids = []
with arcpy.da.SearchCursor(polygon_layer, "OID@") as cursor:
    for row in  cursor:
        selected_oids.append(row[0])

workspace = arcpy.Describe(polygon_layer).path

anzahl_total = 0
try:
    edit = arcpy.da.Editor(workspace)
    edit.startEditing(False, True)
    for oid in selected_oids:
        arcpy.SelectLayerByAttribute_management(polygon_layer, "NEW_SELECTION", "OBJECTID = {0}".format(oid))
        arcpy.SelectLayerByLocation_management(address_layer, "WITHIN", polygon_layer)
        #address_count_within = int(arcpy.GetCount_management(address_layer).getOutput(0))
        #arcpy.AddMessage('Number of address points within Polygon (OBJECTID={0}): {1}'.format(oid, address_count_within))
        with arcpy.da.SearchCursor(address_layer, "Anzahl") as cursor:
            for row in cursor:
                anzahl_total = anzahl_total + row[0]
        #print anzahl_total
            #edit.startOperation()  
            with arcpy.da.UpdateCursor(polygon_layer, ["anzahl"]) as cursor:
                for row in cursor:
                    row[0] = anzahl_total
                    cursor.updateRow(row)
            #edit.stopOperation()
    edit.stopEditing(True)  


finally:
    pass

How can I set the empty value to "0" so that I can sum this? It breaks at This part

with arcpy.da.SearchCursor(address_layer, "Anzahl") as cursor:
                for row in cursor:
                    anzahl_total = anzahl_total + row[0]

This error comes:

 line 29, in <module>
        anzahl_total = anzahl_total + row[0]
    TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Solution

  • To check if row is empty you can test for it like:

    with arcpy.da.SearchCursor(address_layer, "Anzahl") as cursor:
        for row in cursor:
            if row[0] is not None:
                anzahl_total += row[0]
    

    You can also use a generator expression with sum() like:

    with arcpy.da.SearchCursor(address_layer, "Anzahl") as cursor:
        anzahl_total += sum(row[0] for row in cursor if row[0] is not None)