【问题标题】:Select xarray/pandas index based on a list of months根据月份列表选择 xarray/pandas 索引
【发布时间】:2018-06-21 05:07:09
【问题描述】:

我成功实现了来自Select xarray/pandas index based on specific months 的shoyer 回答。

def is_amj(month):
    return (month >= 4) & (month <= 6)

seasonal_data = temp_data.sel(time=is_amj(temp_data['time.month']))

不幸的是,我需要更灵活地选择月份(例如 1 月和 12 月,或 2 月至 11 月,或 1 月、3 月、5 月……)。我想使用月份列表。

我尝试修改代码如下

sel_months = [1,3,5] #in the case of january,march and may

def to_keep(month):
    return (month in sel_months)

seasonal_data = temp_data.sel(time=to_keep(temp_data['time.month']))

但我收到以下消息

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

并且没有找到实施 a.any() 建议的正确方法。

欢迎任何帮助。

【问题讨论】:

  • 试试怎么样:np.isin(month, sel_months)

标签: python pandas numpy python-xarray


【解决方案1】:

我修改了 shoyer 的答案(来自我的问题)并创建了这个小功能。 t_months 是一个像你有几个月的列表。 t2m 可能与您的 temp_data 结构相同。尽管可能有更优雅的解决方案,但它对我来说效果很好。

def extract_months(month, start, end):
    return (month >= start) & (month <= end)


t2m_months = t2m_slice.sel(time=extract_months(t2m_slice['time.month'],t_months[0],t_months[-1]))

【讨论】:

    【解决方案2】:

    COLDSPEED cmets 和 whagi answer 都可以工作,但 https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.in1d.html 建议使用 np.isin,然后我使用 np.isin(month, sel_months)

    【讨论】:

      【解决方案3】:

      我最近一直在考虑这个问题,我同意这种方法有点限制(有时你不想要正好 3 个月......)。因此,每次您需要不同的东西时向函数添加更多参数并不是一个好的解决方案。

      但是,正如您所看到的here,还有另一种方法可以做到这一点,很简单:

      months = [1,2,3,4] # for example season = data.sel(time = np.in1d( data['time.month'], months))

      这样就可以了。

      【讨论】:

        猜你喜欢
        • 2017-03-09
        • 2020-07-02
        • 2013-10-09
        • 2019-08-29
        • 1970-01-01
        • 2017-04-10
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多