python - 将 numpy 数组对象与多个条件进行比较

标签 python arrays numpy conditional-statements

我正在尝试使用 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 , herehere有用,但我找不到问题的答案。

最佳答案

给定(根据您的示例):

>>> 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/

相关文章:

python - .txt 文件中的 NumPy 数组太大,无法加载到内存中

javascript - 检测 JavaScript 中对象数组中是否存在特定值的函数

javascript - 从数组中获取随机值 - Javascript

python - 写入现有的 xlsx 文件,仅覆盖 Python 中的一些工作表

python - 如何重写第三方库使用的方法

python - float 布局 KIVY 中的动画

php - MySQL 中使用 PHP 的多维数组和聚合函数?

python - 使用 for 循环将两个变量一起迭代

python - 条件分段函数

python - 为什么我系统安装的numpy没有matmul?