You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python xarray计算4个GFS温度数据集的日均温数据集

问题描述

我有4个GFS温度数据集,空间分辨率一致,仅时间戳不同,分别对应一天中的00 UTC、06 UTC、12 UTC、18 UTC。我需要计算日均温数据集,有没有自动化的实现方式,不用手动提取对应节点值计算均值再插入数据集?

加载数据集的代码如下:

import xarray as xr

dst00 = xr.open_dataset('gfs.t00z.pgrb2.1p00.f000', engine='cfgrib')
dst06 = xr.open_dataset('gfs.t06z.pgrb2.1p00.f000', engine='cfgrib')
dst12 = xr.open_dataset('gfs.t12z.pgrb2.1p00.f000', engine='cfgrib')
dst18 = xr.open_dataset('gfs.t18z.pgrb2.1p00.f000', engine='cfgrib')
自动化解决方案

有两种高效的自动化方法,无需手动逐个处理节点值:

方法一:用open_mfdataset批量加载并计算

这是最简洁的方式,xarray会自动处理合并和维度对齐:

import xarray as xr

# 定义要处理的文件列表
file_list = [
    'gfs.t00z.pgrb2.1p00.f000',
    'gfs.t06z.pgrb2.1p00.f000',
    'gfs.t12z.pgrb2.1p00.f000',
    'gfs.t18z.pgrb2.1p00.f000'
]

# 批量加载并合并数据集,自动新增time维度
ds_combined = xr.open_mfdataset(
    file_list,
    engine='cfgrib',
    concat_dim='time',
    combine='nested',
    data_vars='minimal'  # 解决可能的元数据不一致问题
)

# 对time维度计算均值,得到日均温
daily_mean_temp = ds_combined.mean(dim='time')

# 保存结果到文件(可选)
daily_mean_temp.to_netcdf('daily_mean_gfs_temp.nc')

方法二:手动加载合并(应对元数据兼容问题)

如果open_mfdataset因元数据报错,可手动为每个数据集添加时间坐标后合并:

import xarray as xr

file_list = [
    'gfs.t00z.pgrb2.1p00.f000',
    'gfs.t06z.pgrb2.1p00.f000',
    'gfs.t12z.pgrb2.1p00.f000',
    'gfs.t18z.pgrb2.1p00.f000'
]

# 批量加载所有数据集
datasets = [xr.open_dataset(f, engine='cfgrib') for f in file_list]

# 为每个数据集添加对应的时间坐标(根据文件名匹配UTC时间)
time_stamps = ['2023-04-05T00:00:00', '2023-04-05T06:00:00', '2023-04-05T12:00:00', '2023-04-05T18:00:00']
for ds, ts in zip(datasets, time_stamps):
    ds.coords['time'] = ts

# 合并为带time维度的数据集
ds_combined = xr.concat(datasets, dim='time')

# 计算日均温
daily_mean_temp = ds_combined.mean(dim='time')

关键注意点

  • 确保所有数据集的空间维度(lat、lon)、变量名完全一致,否则合并会失败
  • 若存在缺失值,可在mean()中添加skipna=True(xarray默认已开启)
  • 保存结果时,NetCDF是通用的气象数据格式,也可根据需求选择其他格式

内容的提问来源于stack exchange,提问作者Outlaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:55:03