如何使用 Numpy 在不同数组中找到相同的行,而不管元素顺序如何?

Jac*_*k.C 5 python numpy pandas

我正在做一个项目,偶然发现了这个问题。我有两个形状为 (8,3) 和 (2,2) 的数组 A 和 B。无论 B 中元素的顺序如何,如何找到 A 中包含 B 每行元素的所有行?

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))
Run Code Online (Sandbox Code Playgroud)

谢谢!

Geo*_*eom 2

这是一种方法:

Import numpy as np

A = np.random.randint(0,5,(8,3))
B = np.random.randint(0,5,(2,2))

C = (A[..., np.newaxis, np.newaxis] == B)
rows = np.where(C.any((3,1)).all(1))[0]
print(rows)
Run Code Online (Sandbox Code Playgroud)

输出:

[0 2 3 4]
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下吗? (2认同)