下载下来的数据变量tp是指日降水数据,但是原始文件为了节省空间,运用了缩放和偏移,scale_factor和add_offset,所以要计算才能得出真正的降水量,而且注意单位是m,一般日降水用的单位是mm。
以下是完整的批量处理代码
import os
import xarray as xr
# 输入和输出目录
input_dir = r'E:\satlite\era5land\ERALAND0'
output_dir = r'E:\satlite\era5land\ERALAND0-out3'
os.makedirs(output_dir, exist_ok=True)
# 遍历输入目录中的所有.nc文件
for filename in os.listdir(input_dir):
if filename.endswith('.nc'):
input_path = os.path.join(input_dir, filename)
# 使用xarray打开NetCDF文件
ds = xr.open_dataset(input_path, engine='netcdf4')
# 读取tp变量的属性并应用偏移和缩放
add_offset = ds.tp.attrs.get('add_offset', 0)
scale_factor = ds.tp.attrs.get('scale_factor', 1)
print(f"Applying offset and scale factor to {filename}...")
# 注意:这里假设你希望将单位转换为毫米(mm),因此乘以1000
ds['precipitation'] = ((ds.tp * scale_factor) + add_offset) * 1000
# 删除原始的tp变量(如果你不再需要它)
del ds['tp']
# 构造输出文件名和路径
output_filename = f"{os.path.splitext(filename)[0]}_adjusted.nc"
output_path = os.path.join(output_dir, output_filename)
# 保存处理后的NC文件
ds.to_netcdf(output_path)
print(f"Processed and saved: {output_path}")
# 注意:这里没有使用geopandas或shapely进行裁剪,只进行了偏移和缩放处理