我有一个包含日期(作为日期时间对象)、价格和作为整数的类别的 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])
