如何基于xarray对多年逐月降水NetCDF数据计算跨年月均值
问题背景
我有一份覆盖1951-1955年的逐月平均降水NetCDF文件,原始xarray.Dataset详情如下:
<xarray.Dataset>
Dimensions: (time: 60, rlat: 412, rlon: 424)
Coordinates:
lat (rlat, rlon) float64 21.99 22.03 22.07 22.11 ... 66.81 66.75 66.69
lon (rlat, rlon) float64 -10.06 -9.964 -9.864 ... 64.55 64.76 64.96
- rlat (rlat) float64 -23.38 -23.26 -23.16 -23.05 ... 21.61 21.73 21.83
- rlon (rlon) float64 -28.38 -28.26 -28.16 -28.05 ... 17.93 18.05 18.16
- time (time) datetime64[ns] 1951-01-01 1951-02-01 ... 1955-12-01
Data variables:
pr (time, rlat, rlon) float32 2.053e-18 2.053e-18 ... 8.882e-06
Attributes: (12/22)
CDI: Climate Data Interface version 1.3.2
Conventions: CF-1.6
NCO: 4.4.2
CDO: Climate Data Operators version 1.3.2 (htt...
contact: Fredrik Boberg, Danish Meteorological Ins...
creation_date: 2019-10-15 18:05:48
... ...
rcm_version_id: v1
project_id: CORDEX
CORDEX_domain: EUR-11
product: output
tracking_id: hdl:21.14103/a879aaf7-ddeb-436a-96fd-b717...
c3s_disclaimer: This data has been produced in the contex...
已通过以下代码筛选出5-10月的逐月降水数据:
out_ds = out_ds.sel(time=out_ds.time.dt.month.isin([5, 6, 7, 8, 9, 10]))
筛选后的数据集详情:
<xarray.Dataset>
Dimensions: (time: 30, rlat: 412, rlon: 424)
Coordinates:
lat (rlat, rlon) float64 21.99 22.03 22.07 22.11 ... 66.81 66.75 66.69
lon (rlat, rlon) float64 -10.06 -9.964 -9.864 ... 64.55 64.76 64.96
- rlat (rlat) float64 -23.38 -23.26 -23.16 -23.05 ... 21.61 21.73 21.83
- rlon (rlon) float64 -28.38 -28.26 -28.16 -28.05 ... 17.93 18.05 18.16
- time (time) datetime64[ns] 1951-05-01 1951-06-01 ... 1955-10-01
Data variables:
pr (time, rlat, rlon) float32 1.957e-18 1.957e-18 ... 1.432e-05
Attributes: (12/22)
CDI: Climate Data Interface version 1.3.2
Conventions: CF-1.6
NCO: 4.4.2
CDO: Climate Data Operators version 1.3.2 (htt...
contact: Fredrik Boberg, Danish Meteorological Ins...
creation_date: 2019-10-15 18:05:48
... ...
rcm_version_id: v1
project_id: CORDEX
CORDEX_domain: EUR-11
product: output
tracking_id: hdl:21.14103/a879aaf7-ddeb-436a-96fd-b717...
c3s_disclaimer: This data has been produced in the contex...
需要计算1951-1955年间5-10月每个月份的多年均值,最终时间维度为6(对应5到10月)。
解决方案
使用xarray的groupby方法按月份分组计算均值,步骤如下:
1. 核心计算代码
# 按时间维度的month属性分组,计算每组的多年均值 monthly_clim = out_ds.groupby('time.month').mean(dim='time')
2. 维度调整(可选)
如果需要将结果的month维度重命名为time,并设置对应的日期标签:
import pandas as pd # 重命名month维度为time monthly_clim = monthly_clim.rename({'month': 'time'}) # 设置time坐标为5-10月的日期(示例用1951年对应月份作为标签) monthly_clim['time'] = pd.date_range(start='1951-05-01', periods=6, freq='MS')
结果说明
执行后monthly_clim的时间维度为6,对应5-10月的多年平均降水数据,维度结构大致如下:
<xarray.Dataset>
Dimensions: (time: 6, rlat: 412, rlon: 424)
Coordinates:
lat (rlat, rlon) float64 ...
lon (rlat, rlon) float64 ...
- rlat (rlat) float64 ...
- rlon (rlon) float64 ...
- time (time) datetime64[ns] 1951-05-01 1951-06-01 ... 1951-10-01
Data variables:
pr (time, rlat, rlon) float32 ...
内容的提问来源于stack exchange,提问作者CoolMathematician

