我有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]
UPDATE为了找到丢失的,请执行以下操作,我将步骤拆分以使其更容易理解:
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
的第一行与a
的第二行匹配。的第二行没有匹配项。
输出的第二部分显示了应用argwhere的结果,该argwhere用于选择在b
(~matches.any(axis=1)
(中不存在与之匹配的a
行的索引。