仅使用冬季数据将xarray数据集重新采样为年度频率

时间:2016-09-15 12:29:15

标签: python python-xarray

我有一个数据集,其中包含多年的每日x,y网格化气象数据。我有兴趣只计算冬季数据的年度平均值,即。不包括夏季数据。

我认为我需要使用resample命令,例如频率AS-OCT将时间序列重新采样到年频率,冬季从每年10月开始(它的北纬)。

我能解决的问题是如何指定我只想使用10月到4月/ 5月的数据,忽略6月,7月和8月。

由于重新采样功能适用于ndarray个对象,我提出了一个相当不可靠的方法来实现这一目的:

def winter(x,axis):
    # Only use data from 1 October to end of April (day 211)
    return np.sum(x[0:211,:,:],axis=0)
win_sum = all_data.resample('AS-OCT',how=winter,dim='TIME')

但我觉得应该有更优雅的解决方案。有什么想法吗?

1 个答案:

答案 0 :(得分:7)

诀窍是为您要排除的日期创建一个掩码。您可以使用groupby来提取月份。

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

# create some example data at daily resolution that also has a space dimension
time = pd.date_range('01-01-2000','01-01-2020')
space = np.arange(0,100)
data = np.random.rand(len(time), len(space))
da = xr.DataArray(data, dims=['time','space'], coords={'time': time, 'space': space})
# this is the trick -- use groupby to extract the month number of each day
month = da.groupby('time.month').apply(lambda x: x).month
# create a boolen Dataaray that is true only during winter
winter = (month <= 4) | (month >= 10)
# mask the values not in winter and resample annualy starting in october
da_winter_annmean = da.where(winter).resample('AS-Oct', 'time')

希望这适合你。它稍微优雅一点,但是这种狡猾的技巧仍然让人觉得有些苛刻。也许还有更好的方法。