arcpy实现分区统计到一张excel中

在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("未找到可处理的数据。")
相关推荐
2501_9307077816 小时前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
leihefeng19 小时前
PX04-用 Python 读 Excel 画折线图,还能直接插回 Excel 文件
python·excel
yanlaifan1 天前
Excel中指定单元格不能输入内容的方法
excel
babe小鑫2 天前
信息与计算科学专业应届生面试 怎么证明自己能解决业务问题
学习·r语言·excel
Data-Miner2 天前
商品ABC分类分析怎么用AI做?脚本复用+图表可编辑的一次完整实操
人工智能·数据分析·excel
E-iceblue5 天前
Excel 列转行/行列转换全指南:从 4 种常见解法到 Python 批量自动化
python·excel·python库·spire.xls
Data-Miner5 天前
AI处理数据的脚本复用与逻辑复用有什么区别?哪种方式更能沉淀工作成果
数据分析·excel
福兮说5 天前
在浏览器里写一个“够用就好“的 Excel 公式求值器
前端·javascript·excel·编译原理
慧都小妮子6 天前
标签打印如何减少手工抄数?用Bartender 直连 Excel 批量打印
excel·bartender·条码打印·标签打印软件·数据驱动打印·工业打印机
SunnyDays10116 天前
Java 设置 Excel 数据验证:整数、日期、文本长度、下拉列表和时间
java·excel·数据验证·下拉列表