我想基于1d矩阵中的日期将2d日期矩阵转换为布尔矩阵。即,
[[20030102, 20030102, 20070102],
[20040102, 20040102, 20040102].,
[20050102, 20050102, 20050102]]
应该成为
[[True, True, False],
[False, False, False].,
[True, True, True]]
如果我提供1d阵列[20010203, 20030102 ,20030501, 20050102 ,20060101]
答案 0 :(得分:4)
import numpy as np
dateValues = np.array(
[[20030102, 20030102, 20030102],
[20040102, 20040102, 20040102],
[20050102, 20050102, 20050102]])
requestedDates = [20010203, 20030102, 20030501, 20050102, 20060101]
ix = np.in1d(dateValues.ravel(), requestedDates).reshape(dateValues.shape)
print(ix)
<强>返回:强>
[[ True True True]
[False False False]
[ True True True]]
有关更多信息(文档),请参阅numpy.in1d
:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html
答案 1 :(得分:1)
a = np.array([[20030102, 20030102, 20070102],
[20040102, 20040102, 20040102],
[20050102, 20050102, 20050102]])
b = np.array([20010203, 20030102, 20030501, 20050102, 20060101])
>>> a.shape
(3, 3)
>>> b.shape
(5,)
>>>
为了进行比较,您需要b
a
向[{1}}添加一个轴a
。 - 这会将a
的每个元素与b
>>> mask = a[...,None] == b
>>> mask.shape
(3, 3, 5)
>>>
然后使用np.any()
查看是否有任何匹配
>>> np.any(mask, axis = 2, keepdims = False)
array([[ True, True, False],
[False, False, False],
[ True, True, True]], dtype=bool)
timeit.Timer与in1d
比较:
>>>
>>> t = Timer("np.any(a[...,None] == b, axis = 2)","from __main__ import np, a, b")
>>> t.timeit(10000)
0.13268041338812964
>>> t = Timer("np.in1d(a.ravel(), b).reshape(a.shape)","from __main__ import np, a, b")
>>> t.timeit(10000)
0.26060646913566643
>>>