【Python】Arcpy栅格批量掩膜并求平均值

批量掩膜,并求掩膜后文件的平均值,导出到excel中。

import arcpy
from arcpy.sa import *
import pandas as pd
import os
# 设置路径
tif_file_path = r"E:\Data\tif" # tif数据路径
shp_file = r"E:\City.shp" #矢量数据路径及名称

out_file_path=r"E:\Data\City"
output_excel_path = os.path.join(out_file_path, "city_mean.xlsx")

# 设置工作空间和范围
arcpy.env.workspace = tif_file_path
arcpy.env.extent = shp_file
# 创建输出文件夹
if not os.path.exists(out_file_path):
    os.makedirs(out_file_path)
# 列出所有TIF文件
tif_file_names = arcpy.ListRasters("*", "TIF")

# 创建一个空的DataFrame来存储结果
results = pd.DataFrame(columns=["TIF File", "Value"])

# 处理每个TIF文件
for tif_file in tif_file_names:
    # 提取掩膜结果
    mask_result = ExtractByMask(tif_file, shp_file)
    mask_result_path = os.path.join(out_file_path, tif_file.replace(".tif", "_city.tif"))
    mask_result.save(mask_result_path)

    # 计算掩膜结果的平均值
    mean_value = arcpy.GetRasterProperties_management(mask_result, "MEAN")
    mean_value = float(mean_value.getOutput(0))

    # 将结果添加到DataFrame
    results = results.append({
        "TIF File": tif_file, #或者读取文件名中的某部分,如日期"TIF File": tif_file[3:-4]
        "Value": mean_value
    }, ignore_index=True)

# 按照文件名对DataFrame进行排序
results = results.sort_values(by="TIF File")

# 将结果保存到Excel文件
results.to_excel(output_excel_path, index=False)

print("Process completed and results saved to:", output_excel_path)
``
  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值