栅格数据批量求每个数据都平均值,导出到excel中。
import arcpy
import pandas as pd
import os
# 设置路径
tif_file_path = r"E:\Data\EF"
out_file_path = r"F:\1Data\EF"
output_excel_path = os.path.join(out_file_path, "EF.xlsx")
# 设置工作空间
arcpy.env.workspace = tif_file_path
# 创建输出文件夹如果它不存在
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=["DATE", "EF"])
# 处理每个TIF文件
for tif_file in tif_file_names:
# 构造完整的TIF文件路径
tif_full_path = os.path.join(tif_file_path, tif_file)
# 使用CalculateStatistics_management函数计算统计信息
arcpy.management.CalculateStatistics(tif_full_path)
# 计算栅格均值
mean_value = arcpy.GetRasterProperties_management(tif_full_path, "MEAN")
# 获取均值结果
mean_value = float(mean_value.getOutput(0))
print(tif_file[3:-4])
# 将结果添加到DataFrame
results = results.append({
"DATE": tif_file[3:-4],
"EF": 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)