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

Resample xarray Dataset to annual frequency using only winter data

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

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

我无法解决的是如何指定我只想使用从 10 月到 April/May 的数据,而忽略 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')

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

诀窍是为您希望排除的日期创建一个掩码。您可以使用 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')

希望这对你有用。它稍微优雅一些​​,但 groupby 技巧仍然感觉有点老套。也许还有更好的办法。