我有 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)
).