arcpy实现分区统计到一张excel中
2026/7/20 15:33:12 网站建设 项目流程

在arcpy中我们通常需要分区统计来计算值,而且分区统计的时候需要统计多个栅格的情况。因而,我写了这个代码,以期待给大家进行分享。

# 分区统计到表# 裁剪到指定区域importosimportsubprocess#路径shpfile=r"C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\26植被分区\26内蒙植被分区.shp"output_file_dbf=r"C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\zone_dbf"output_file_exc=r"C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\zone_excel"os.makedirs(output_file_dbf,exist_ok=True)os.makedirs(output_file_exc,exist_ok=True)# to sum excelto_sumfile=r'C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\merged_output.xlsx'# 栅格数据路径env_workspace=r"C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\内蒙植被覆盖度mask"

下面是具体的代码情况。

importpandasaspdfromarcpyimportenvimportarcpyimportosfromarcpy.saimport*importsys# # 解析命令行参数# output_file_dbf = sys.argv[1]# output_file_exc = sys.argv[2]# to_sumfile = sys.argv[3]# env_workspace = sys.argv[4]# shpfile = sys.argv[5]# 设置默认值,如果没有给值的话# if len(sys.argv) < 7:# zoneField = "WYZ" # 默认分区字段# else:# zoneField = sys.argv[6]zoneField="WYZ"# 默认分区字段## 参数设置# 要提取的列索引 # 注意:索引从0开始col_indices=[1,5]# 分区的类型zone_type=1#### 栅格数据路径env_workspace=env_workspace#E:\BaiduSyncdisk\西安生态修复论文\zone_analyse\workspace\zone_analyse\ES\indicatorenv.workspace=env_workspace rasterlist=arcpy.ListRasters("*","TIF")# 允许重复写入arcpy.gp.overwriteOutput=Truedefzone_stat(inZoneData,zoneField,inValueRaster,outTable):# Check out the ArcGIS Spatial Analyst extension licensearcpy.CheckOutExtension("Spatial")# Execute ZonalStatisticsAsTableZonalStatisticsAsTable(inZoneData,zoneField,inValueRaster,outTable,"DATA","ALL")#,percentile_values = "90"forrasterinrasterlist:save_path=os.path.join(output_file_dbf,os.path.basename(raster))# E:\BaiduSyncdisk\西安生态修复论文\zone_analyse\workspace\zone_analyse\ES\region_zone# 统计栅格数据在矢量区域内的统计值zone_stat(shpfile,zoneField,raster,save_path)print(save_path)# 这块有个伴随生成的东西,我不清楚如何删除它。后续可以弄明白。print("Finshed")#==========def to excelenv.workspace=output_file_dbf excel_file=arcpy.ListTables("*","ALL")num=len(excel_file)foriinrange(0,num):env.workspace=output_file_dbf excel_file=arcpy.ListTables("*","ALL")# Creat folder and name fileoutput_file=output_file_excifos.path.lexists(output_file)==False:# 判断系统是否存在该指定路径,若不存在则创建该路径与子文件夹os.makedirs(output_file)Save_name=excel_file[i][:-4]+".xls"save_path=os.path.join(output_file,Save_name)# Export datearcpy.TableToExcel_conversion(excel_file[i],save_path,"NAME","CODE")#arcpy_table_excel.table_to_excel(excel_file[i], save_path)print(Save_name)print("finished")print(num)# 设置文件夹路径folder_path=output_file_exc# 替换为你自己的路径output_file=to_sumfile# 存放每个文件提取后的 DataFramemerged_columns=[]# 遍历文件夹中所有 .xls 文件forfilenameinos.listdir(folder_path):iffilename.endswith('.xls'):file_path=os.path.join(folder_path,filename)try:df=pd.read_excel(file_path,engine='xlrd')selected=df.iloc[:,col_indices]# 获取原始列名original_colnames=df.columns[col_indices]# 重命名:文件名_原始列名new_colnames=[f"{filename}_{col}"forcolinoriginal_colnames]selected.columns=new_colnames# 重置索引以确保行对齐(可选)selected=selected.reset_index(drop=True)merged_columns.append(selected)exceptExceptionase:print(f"处理文件{filename}出错:{e}")# 横向合并所有 DataFrameifmerged_columns:final_df=pd.concat(merged_columns,axis=1)final_df.to_excel(output_file,index=False)print(f"成功保存为{output_file}")else:print("未找到可处理的数据。")

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询