【问题标题】:indexing on datetime object within a numpy array在 numpy 数组中对日期时间对象进行索引
【发布时间】:2016-11-04 12:16:51
【问题描述】:

我有一个 numpy 数组,其中包含日期(作为日期时间对象)、价格和作为整数的类别:

array([[datetime.date(2013, 6, 5), 11.42, 1],
   [datetime.date(2013, 6, 7), 63.97, 1],
   [datetime.date(2013, 6, 19), 3.92, 1],
   [datetime.date(2013, 6, 19), 16.25, 2],
   [datetime.date(2013, 6, 20), 11.0, 2],
   [datetime.date(2013, 6, 22), 32.72, 2],
   [datetime.date(2013, 6, 25), 16.6, 3],
   [datetime.date(2013, 6, 26), 2.95, 2],
   [datetime.date(2013, 7, 1), 6.27, 1],
   [datetime.date(2013, 7, 1), 2.95, 1]], dtype=object)

如果通过index_cat=(array==2).any(axis=1) 满足一个类别,然后通过np.sum(array[index_cat][:,1]) 来总结价格是显而易见的。

我现在想要实现的基本一样,只是我不想选择一个类别,而是想以datetime对象的月份或月-年组合为标准。

所以我认为 index_june=(array==datetime.dateime(month='06').any(axis=1) 应该这样做,但是,即使进行了大量搜索,我也找不到这样做的方法。

那么,考虑到没有通配符,我该如何表达这个来匹配日期时间对象呢?

提前非常感谢!

【问题讨论】:

    标签: python arrays datetime numpy indexing


    【解决方案1】:

    你可以使用numpy的vectorize函数:

    getmonth = np.vectorize(lambda d: getattr(d, "month"))
    ind = getmonth(arr[:,0]) == 11
    

    另一种方法是列表理解:

    ind = np.array([a[0].month == 11 for a in arr])
    

    【讨论】:

    • 太棒了!感谢您快速明确的回答!我更喜欢列表理解方式,因为它更适合我的 python 知识(现在)..
    • 好像也快了一点。
    猜你喜欢
    • 2021-11-05
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2021-07-22
    相关资源
    最近更新 更多