如何将空值设置为零

how to set empty value to zero

我在代码中设置了 table "address_layer"。在那里我试图对列 "Anzahl" 求和。 问题是在值为 Empty(其中没有任何内容)的情况下,代码会中断。

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

如何将空值设置为“0”以便我可以求和? 它在这部分中断

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

出现这个错误:

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

要检查行是否为空,您可以test for it喜欢:

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

您还可以使用 generator expression with sum(),例如:

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