我有一个文件是一年的月度数据(12分)。数据从12月开始,到11月结束。我希望创建一个为期3个月的平均文件,即DJF,JFM,...,SON(10分)
我注意到有一个DataArray.rolling
函数返回一个滚动窗口选项,我认为这对此有用。但是,我没有找到使用滚动功能的任何示例。我承认我不熟悉bottleneck,pandas.rolling_mean
或更近期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:应该提供一个暗淡/窗口
答案 0 :(得分:1)
你非常接近。 rolling method采用映射为dim
/ window_size
的键/值对。这应该适合你。
da.rolling(time=3).mean()