python-xarray:滚动平均示例

python-xarray: rolling mean example

我有一个文件,是一年的月度数据(12 点)。数据从 12 月开始,到 11 月结束。我希望创建一个 3 个月 运行 的平均文件,它将是 DJF、JFM、...、SON(10 分)

我注意到有一个 DataArray.rolling function which returns a rolling window option and I think would be useful for this. However, I haven't found any examples using the rolling function. I admit i'm not familiar with bottleneck, pandas.rolling_mean or the more recent pandas.rolling 所以我的入门水平相当低。

下面是一些要测试的代码:

import numpy as np
import pandas as pd
import xarray as xr

lat = np.linspace(-90, 90, num=181); lon = np.linspace(0, 359, num=360)
# Define monthly average time as day in middle of month
time = pd.date_range('15/12/1999', periods=12, freq=pd.DateOffset(months=1))
# Create data as 0:11 at each grid point
a = np.linspace(0,11,num=12)
# expand to 2D
a2d = np.repeat(tmp[:, np.newaxis], len(lat), axis=1)
# expand to 3D
a3d = np.repeat(a2d[:, :, np.newaxis], len(lon), axis=2)
# I'm sure there was a cleaner way to do that...

da = xr.DataArray(a3d, coords=[time, lat, lon], dims=['time','lat','lon'])  

# Having a stab at the 3-month rolling mean
da.rolling(dim='time',window=3).mean()
# Error output:
Traceback (most recent call last):
File "<ipython-input-132-9d64cc09c263>", line 1, in <module>
da.rolling(dim='time',window=3).mean()
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/common.py", line 478, in rolling
center=center, **windows)
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/rolling.py", line 126, in __init__
center=center, **windows)
File "/Users/Ray/anaconda/lib/python3.6/site-packages/xarray/core/rolling.py", line 62, in __init__
raise ValueError('exactly one dim/window should be provided')

ValueError:应该提供一个dim/window

你们很亲近。 rolling method 采用映射为 dim/window_size 的 key/value 对。这应该适合你。

da.rolling(time=3).mean()