点击蓝字 关注我们
把多年逐小时气温数据处理成
多年逐日最高最低平均气温数据
数据链接
import xarray as xr
import numpy as np
import os
# 设置路径
data_path = "J:/2m_Temperature/"
output_path = "D:/lizhi/land_atmosphere_heatwaves/2m_tem/"
# 创建输出目录(如果不存在)
os.makedirs(output_path, exist_ok=True)
# 分年处理数据
years = np.arange(1940, 2024)
for year in years:
print(f"Processing year: {year}")
# 获取当前年份所有文件的路径
year_files = [os.path.join(data_path, f"era5.2mt.{year}{month:02d}{day:02d}.nc")
for month in range(1, 13) for day in range(1, 32)
if os.path.exists(os.path.join(data_path, f"era5.2mt.{year}{month:02d}{day:02d}.nc"))]
# 初始化空的数据数组
daily_max_t2m = None
daily_min_t2m = None
daily_mean_t2m = None
for file in year_files:
try:
# 逐个文件处理
ds = xr.open_dataset(file)
t2m = ds['t2m']
# 获取并应用缩放因子和偏移量
scale_factor = t2m.attrs.get('scale_factor', 1.0)
add_offset = t2m.attrs.get('add_offset', 0.0)
t2m = t2m * scale_factor + add_offset # 应用缩放因子和偏移量
# 将温度从K转换为C
t2m = t2m - 273.15
# 计算每日最高、最低和平均温度
max_t2m = t2m.max(dim='time')
min_t2m = t2m.min(dim='time')
mean_t2m = t2m.mean(dim='time')
# 累加每日数据
if daily_max_t2m is None:
daily_max_t2m = max_t2m
daily_min_t2m = min_t2m
daily_mean_t2m = mean_t2m
else:
daily_max_t2m = xr.concat([daily_max_t2m, max_t2m], dim='time')
daily_min_t2m = xr.concat([daily_min_t2m, min_t2m], dim='time')
daily_mean_t2m = xr.concat([daily_mean_t2m, mean_t2m], dim='time')
# 关闭当前文件
ds.close()
except Exception as e:
print(f"Error processing file {file}: {e}")
# 将结果保存为NetCDF文件
if daily_max_t2m is not None:
output_ds = xr.Dataset({
'daily_max_t2m': daily_max_t2m,
'daily_min_t2m': daily_min_t2m,
'daily_mean_t2m': daily_mean_t2m
})
output_file = os.path.join(output_path, f'daily_temperatures_{year}.nc')
output_ds.to_netcdf(output_file)
print(f"Year {year} results saved to {output_file}")
print("所有年份的数据处理完毕!")
END
后台私信:第八星系
群内每日更新分享数据
进群请勿回复第八星系以外字词
编辑:第八星系-欣悦