[ArcPy Tips-5] 矢量版的Zonal Statistics As Table (仅面积)

ArcGIS 自带的 Zonal Statistics As Table 在分区统计栅格面积时很好用,但是这个工具只能针对栅格,不能针对矢量。
最近有这个需求,所以就做了一个,基本都是 ArcPy 的自带函数,输入的参数和 Zonal Statistics As Table 高度类似,在此不作详细解释,请君查看代码。
下附:

import arcpy,os,pandas,shutil

def write2DListToCsv(listItem,fileName):
    fileObject = open(fileName, 'w')
    for i in range(len(listItem)):
        for j in range(len(listItem[i])):
            fileObject.write(str(listItem[i][j]))
            if j < len(listItem[i])-1:
                fileObject.write(",")
        if  i < len(listItem)-1: 
            fileObject.write("\n")
    fileObject.close()

def main():
    maskShp = r"E:\xxx\xxx.shp"
    valueField = "xxxID"
    polygon = r"E:\xxx\xxx.shp"
    dstFile = r"E:\xxx\xxx.shp"
    
    tempDir = "E:\\xxx\\xxx\\temp\\"
    masksDir = tempDir+"masks\\"

    shutil.rmtree(tempDir)
    os.mkdir(tempDir)
    os.mkdir(masksDir)

    table = [[valueField,"AREA"]]
    arcpy.Split_analysis(maskShp,maskShp,valueField,masksDir)

    for mask in os.listdir(masksDir):
        if not os.path.splitext(mask)[1] == ".shp":
            continue
        print(mask)
        value = mask[0:-4]
        tempFile = value+".shp"
        arcpy.Clip_analysis(polygon,masksDir+mask,tempDir+tempFile)
        featureCount = arcpy.GetCount_management(tempDir+tempFile)[0]
        if int(featureCount)>0:
            arcpy.CalculateAreas_stats(tempDir+tempFile, tempDir+"AREA_"+tempFile)
            arcpy.TableToTable_conversion(tempDir+"AREA_"+value+".dbf",tempDir,value+".csv")
            areaSum = pandas.read_csv(tempDir+value+".csv")["F_AREA"].sum()
            print(areaSum)
            table.append([value,areaSum])
    print(table)
    write2DListToCsv(table,dstFile)

if __name__ == "__main__":
	main()
posted @ 2022-03-21 15:15  wsZhang  阅读(651)  评论(0编辑  收藏  举报