2d数组的numpy掩码,所有值都在1d数组中

时间:2016-09-09 13:51:19

标签: python numpy

我想基于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]

2 个答案:

答案 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.in1dhttp://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
>>>