2017-09-01 55 views
0

我有一個文件,它是一年的每月數據(12分)。數據從12月開始,到11月結束。我希望創建一個3個月的平均文件,這將是DJF,JFM,...,SON(10分)python-xarray:滾動平均值示例

我注意到有一個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

你非常接近。 rolling method需要一個映射爲dim/window_size的鍵/值對。這應該適合你。

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

謝謝。我認爲最簡單的方法是刪除nans,只需要 da.rolling(time = winlen).mean()[winlen-1 ::,:,] 不確定是否有更好的東西。 請記住,如果我做一個小小的PR,將此示例添加到DOC的https://github.com/pydata/xarray/blob/master/xarray/core/rolling.py 是否有可用功能的列表滾動對象,例如平均數,總和,中位數等? –

+1

所以你可以做兩件事來幫助nans:1)你可以設置'min_periods'爲一個整數(例如'da.rolling(min_periods = 0,time = 3).mean()'),或者2)你可以使用'dropna'(例如da.rolling(time = 3).mean()。dropna('time)')來刪除NaNs。我們一直致力於幫助改善xarray文檔。 – jhamman