在arcpy中我们通常需要分区统计来计算值,而且分区统计的时候需要统计多个栅格的情况。因而,我写了这个代码,以期待给大家进行分享。
python
# 分区统计到表
# 裁剪到指定区域
import os
import subprocess
#路径
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 excel
to_sumfile = r'C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\merged_output.xlsx'
# 栅格数据路径
env_workspace = r"C:\Users\DELL\Desktop\内蒙生态系统评估FIN\内蒙生态系统评估\data\生态退化\内蒙植被覆盖度mask"
下面是具体的代码情况。
python
import pandas as pd
from arcpy import env
import arcpy
import os
from arcpy.sa import *
import sys
# # 解析命令行参数
# 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\indicator
env.workspace = env_workspace
rasterlist = arcpy.ListRasters("*", "TIF")
# 允许重复写入
arcpy.gp.overwriteOutput = True
def zone_stat(inZoneData,zoneField,inValueRaster,outTable):
# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spatial")
# Execute ZonalStatisticsAsTable
ZonalStatisticsAsTable(inZoneData, zoneField, inValueRaster,
outTable, "DATA", "ALL")#,percentile_values = "90"
for raster in rasterlist:
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 excel
env.workspace = output_file_dbf
excel_file = arcpy.ListTables("*","ALL")
num = len(excel_file)
for i in range(0,num):
env.workspace = output_file_dbf
excel_file = arcpy.ListTables("*","ALL")
# Creat folder and name file
output_file = output_file_exc
if os.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 date
arcpy.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
# 存放每个文件提取后的 DataFrame
merged_columns = []
# 遍历文件夹中所有 .xls 文件
for filename in os.listdir(folder_path):
if filename.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}" for col in original_colnames]
selected.columns = new_colnames
# 重置索引以确保行对齐(可选)
selected = selected.reset_index(drop=True)
merged_columns.append(selected)
except Exception as e:
print(f"处理文件 {filename} 出错:{e}")
# 横向合并所有 DataFrame
if merged_columns:
final_df = pd.concat(merged_columns, axis=1)
final_df.to_excel(output_file, index=False)
print(f"成功保存为 {output_file}")
else:
print("未找到可处理的数据。")