我正在尝试使用 numpy.where
来查找我想要的索引。这是代码:
import numpy as np
a = np.array([20,58,32,0,107,57]).reshape(2,3)
item_index = np.where((a == 58) | (a == 107) | (a == 20))
print item_index
我得到 item_index
如下:
(array([0, 0, 1]), array([0, 1, 1]))
然而,在现实中,a
的维度是 20000 x 7
并且条件是几百个而不是三个。有没有办法在多个条件下使用 numpy.where
?我找到了主题 here , here和 here有用,但我找不到问题的答案。
最佳答案
给定(根据您的示例):
>>> a
array([[ 20, 58, 32],
[ 0, 107, 57]])
对于查询,“是值列表中 a 的数组元素”,只需使用 numpy.in1d :
>>> np.in1d(a, [58, 107, 20])
array([ True, True, False, False, True, False], dtype=bool)
如果您希望索引与底层数组相同,只需重新整形为a
的形状:
>>> np.in1d(a, [58, 107, 20]).reshape(a.shape)
array([[ True, True, False],
[False, True, False]], dtype=bool)
然后测试一下:
>>> tests=np.in1d(a, [58, 107, 20]).reshape(a.shape)
>>> tests[1,1] # is the element of 'a' in the list [58, 107, 20]?
True
在一行中(很明显,但我不知道对于一次性查询是否有效):
>>> np.in1d(a, [58, 107, 20]).reshape(a.shape)[1,1]
True
关于python - 将 numpy 数组对象与多个条件进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027129/