【问题标题】:Resample xarray Dataset to annual frequency using only winter data仅使用冬季数据将 xarray 数据集重新采样为年频率
【发布时间】:2017-01-23 11:27:04
【问题描述】:

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

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

我无法解决的是如何指定我只想使用从 10 月到 4 月/5 月的数据,而忽略 6 月、7 月和 8 月。

由于 resample 函数适用于 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')

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

【问题讨论】:

  • Python 没有重采样功能。如果您使用的是 Pandas,请将标签添加到您的问题中。
  • 这个问题是关于一个 xarray 数据集而不是一个熊猫数据帧。
  • 您是否尝试过屏蔽(使用.where)然后重新采样?我认为您会发现这比尝试将掩蔽合并到重新采样中要容易得多。如果你有一个完全重现的例子,我可以用一个例子来回应

标签: python python-xarray


【解决方案1】:

诀窍是为您希望排除的日期创建一个掩码。您可以通过使用 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 技巧仍然感觉有点 hackish。也许还有更好的方法。

【讨论】:

  • 提取每个数据点的月份数的技巧对于任何类型的切片和过滤都非常有用。
猜你喜欢
  • 2019-07-18
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多