python - 如何在另一个 ndarray 中找到一个 ndarray 的索引

标签 python python-3.x numpy indexing

<分区>

我有 a = np.arange(21).reshape(7,3)b = np.array([[3,4,5], [9 ,10,11]])

a = [[ 0  1  2]
     [ 3  4  5]
     [ 6  7  8]
     [ 9 10 11]
     [12 13 14]
     [15 16 17]
     [18 19 20]]

b = [[3  4  5]
     [9 10 11]]

我想在 a 中找到 b 的行号。因此,我希望将 1 和 3 作为我的输出。我知道要找到索引,我可以使用 np.where()np.argwhere()。但是,我不知道我们是否可以使用它们来解决这个问题,或者我必须使用其他功能。我尝试了 c = np.argwhere(a == b) 但它给出了错误。

最佳答案

你可以使用 np.argwhere如下:

import numpy as np

a = np.array([[0, 1, 2],
              [3, 4, 5],
              [6, 7, 8],
              [9, 10, 11],
              [12, 13, 14],
              [15, 16, 17],
              [18, 19, 20]])

b = np.array([[3, 4, 5],
              [9, 10, 11]])

res = np.argwhere(
    (a == b[:, None])  # compare all rows of a vs b
    .all(axis=2)  # find the ones where all the elements matches
)[:, 1]  # use argwhere to find indices, but only use the column indices

print(res)

输出

[1 3]

更新 为了找到丢失的部分,请执行以下操作,我拆分了这些步骤以使其更容易理解:

matches = (a == b[:, None]).all(axis=2)
print(matches)

res = np.argwhere(~matches.any(axis=1))[:, 0]
print(res)

输出

[[False  True False False False False False]
 [False False False False False False False]]
[1]

输出的第一部分,显示了与 b 中的行对应的两行,因为可以看出 b 的第一行与 with 匹配a 的第二行。第二行,没有匹配项。

输出的第二部分显示应用 argwhere 选择索引的结果,其中 a 的行与 b 中的行不匹配(~匹配.any(轴=1)).

关于python - 如何在另一个 ndarray 中找到一个 ndarray 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65112727/

相关文章:

python - imap - 如何删除消息

python - 如何使用 Python 改变正则表达式中的替换字符串?

python - 如何有条件地将一个热向量添加到 Pandas DataFrame

python - 在python中将数组显示为光栅图像

numpy - 'numpy.float64' 对象不可调用

python - 如何在数字列表上实现模数?

javascript - TemplateSyntaxError 无法解析其余部分

python - Django queryset dict in dict 跨 ForeignKey

python - 如何将 dunder 方法 monkeypatch 到现有实例?

Python NUMPY HUGE 矩阵乘法