如何在 numpy 数组中查找元素的索引?

How to find the index of an element in an numpy array?

我有一个数组 df,其中每个元素都是 2 个数字的列表。给定一个元素 p = [18, 169]。我想在 df 中找到这些元素 p 的索引。鉴于 df

[[[13, 169],    [18, 169],  [183, 169]],
 [[-183, 169],  [18, 169],  [183, 169]],
 [[18, 169],    [-18, 169], [183, 169]]]

有了(df == p).all(-1),我得到

array([[False,  True, False],
       [False,  True, False],
       [ True, False, False]])

我要的是

[[0, 1],
 [1, 1],
 [2, 0]]

能否请您详细说明如何操作?

import numpy as np
df = np.array([[[13, 169],   [18, 169], [183, 169]],
               [[-183, 169], [18, 169], [183, 169]],
               [[18, 169],   [-18, 169], [183, 169]]])
p = [18, 169]
ind = (df == p).all(-1)
ind

你用 (df==p).all(-1) 计算的是一个 掩码。它们有很多用途,但您可以直接使用它来计算您想要的值。

# True or false at each coordinate
mask = (df==p).all(-1)

# Extract the coordinates where the mask is True
result = np.argwhere(mask)