在 python 中使用 xarray 获取每月气候数据

Getting monthly climatology using xarray in python

我有一个 netCDF 文件,其中包含名为 var2001-01-01 到 2010-12-31 的变量的每日数据。我想计算 var 的每月总和,得到一个包含 12 个时间步长的 netCDF(一年中的每个月一个)。目前,我正在这样做:

import xarray as xr
hndl_fl = xr.open_dataset(path_file)

hndl_fl.resample('1MS', dim='time', how='sum')

但是,这会生成一个 netCDF,其中包含从 2001 年到 2010 年每个月的月度总和。我如何获得 12 个月的月平均值?

Comments: I am looking for monthly average for 12 months (for all years from 2001 to 2010). Your solution only computes monthly average for 1 year

我的第一个输出从2001-01开始到2010-12,所以所有年份都包括在内。
您要再次 resample 这些 120 值吗?


How do i get the monthly average for 12 months?

你必须决定你想要什么:
一年内每个月的平均值,每年产生 12 个值,10 年最多 120 个值

1 年的平均值,在 10 年内产生 10 个值

使用以下xarray.Dataset,date_range=10年

date_range('2001-01-01', '2010-12-31', name='time')
<xarray.Dataset>
Dimensions:  (time: 3652)
Coordinates:
  * time     (time) datetime64[ns] 2001-01-01 2001-01-02 2001-01-03 ...
Data variables:
    data     (time) float64 16.0 18.0 15.0 12.0 23.0 9.0 7.0 18.0 23.0 23.0 ...

获取 date_range('2001-01-01', '2010-12-31', name='time') 中每个月的 monthly_avr

monthly_avr = ds.resample('1MS', dim='time', how='mean')

输出:

monthly_avr=<xarray.Dataset>
Dimensions:  (time: 120)
Coordinates:
  * time     (time) datetime64[ns] 2001-01-01 2001-02-01 2001-03-01 ...
Data variables:
    data     (time) float64 17.42 16.54 19.23 18.37 14.74 17.8 16.45 17.29 ...

获取 date_range('2001-01-01', '2010-12-31', name='time') 中每一年的 year_avr :

year_avr = ds.resample('1AS', dim='time', how='mean')  

输出:

year_avr=<xarray.Dataset>
Dimensions:  (time: 10)
Coordinates:
  * time     (time) datetime64[ns] 2001-01-01 2002-01-01 2003-01-01 ...
Data variables:
    data     (time) float64 17.22 17.13 17.05 17.49 17.38 17.07 16.72 16.47 ...  

测试 Python:3.4.2 - xarray: 0.9.1

两者都

hndl_fl.resample('1MS', dim='time', how='mean')

hndl_fl.groupby('time.month').mean('time')

应该可以解决问题,具体取决于您想要什么。