如何将空值设置为零

时间:2018-09-16 20:06:45

标签: python arcmap

我在代码中设置了一个表“ 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'

1 个答案:

答案 0 :(得分:2)

要检查行是否为空,您可以像这样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 expressionsum()一起使用,例如:

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