批量掩膜,并求掩膜后文件的平均值,导出到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)
``