python - 在多维numpy数组中查找多个查询的索引

标签 python arrays numpy multidimensional-array

我正在寻找一种在多维数组中查找查询数组索引的方法。例如:

arr = np.array([[17,  5, 19,  9],
   [18, 13,  3,  7],
   [ 8,  1,  4,  2],
   [ 8,  9,  7, 19],
   [ 6, 11,  8,  5],
   [11, 16, 13, 18],
   [ 0,  1,  2,  9],
   [ 1,  7,  4,  6]])

我可以找到一个查询的索引:

np.where(arr==1)
# (array([2, 6, 7]), array([1, 1, 0]))

是否有任何 numpy 解决方案可以对多个值执行此操作,以替换以下 for 循环?

for q in queries:
    np.where(arr==q)

如果数组和查询都是一维的,我可以使用 searchsorted 作为 this answer但它不适用于多维数组。

最佳答案

IIUC你可以尝试这个:

In[19]:np.where((arr==4)|(arr==5))
Out[19]: (array([0, 2, 4, 7], dtype=int64), array([1, 2, 3, 2], dtype=int64))

关于python - 在多维numpy数组中查找多个查询的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39159548/

相关文章:

检查子串是否在主串中,如果是,从找到的子串开始打印主串

python - 在 python : averaging last n entries of a column 中找到价格动量的有效方法

python - 在没有循环的情况下在 python 中返回列表索引的优雅方法是什么?

python - 如何执行两个列表的元素乘法?

python - 有效地减去不同形状的numpy数组

java - Java 中文件中的数组数组

java - 使用方法在数组中搜索唯一名称

python - 将 Pandas 列转换为用于 Keras 神经网络的 Numpy 数组

numpy - 带有字符串输入的 Tensorflow 数据集不保留数据类型

python - 如何从 JSON 列表创建 pandas.DataFrame