检查列表中的值是否在numpy数组的相应行中

时间:2018-06-28 13:22:33

标签: python arrays numpy

b =np.ndarray(shape=(5,5), dtype=int, order='F')
Out[142]: 
array([[       1,    65536,        0,        0,        0],
       [       0,        0,        1,    65536,        0],
       [16777216,        0,        0,        0,        1],
       [       0,      256, 16777216,        0,        0],
       [       0,        0,        0,      256, 16777216]])

,我有一个列表,例如:

a = [1,23,4,5,20,0...]

我想检查每个索引是否a中的值是否在b的对应行中,如np.isin(a[0], b[0])并接收所有行的布尔向量(如果{ {1}}在a[i]中。

b[i]的长度等于a的长度(行数)。

1 个答案:

答案 0 :(得分:1)

这是使用np.ndarray.any的一种方法。只需注意对齐尺寸以允许广播。

np.random.seed(0)

b = np.random.randint(0, 10, (5, 5))
a = np.random.randint(0, 10, 5)

print(a, b, sep='\n'*2)

[3 0 3 5 0]

[[5 0 3 3 7]
 [9 3 5 2 4]
 [7 6 8 8 1]
 [6 7 7 8 1]
 [5 9 8 9 4]]

c = (a[:, None] == b).any(1)

print(c)

array([ True, False, False, False, False], dtype=bool)