gpt4 book ai didi

python - 在 numpy 数组中索引日期时间对象

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:49 25 4
gpt4 key购买 nike

我有一个包含日期(作为日期时间对象)、价格和作为整数的类别的 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) 应该这样做,但是,即使进行了大量搜索,我找不到执行此操作的方法。

那么,考虑到没有通配符,我该如何表达它来匹配 datetime 对象呢?

提前致谢!

最佳答案

您可以使用 numpy 的向量化函数:

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 - 在 numpy 数组中索引日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com