[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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!