5

I was working on a project and stumbled upon this problem. I have two arrays A and B of shape (8,3) and (2,2). How can I find all the rows of A that contain elements of each row of B regardless of the order of the elements in B?

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

Thanks!

Jack.C
  • 61
  • 4

2 Answers2

2

Here is a one way to do it:

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)

Output:

[0 2 3 4]
Geom
  • 1,491
  • 1
  • 10
  • 23
2
import numpy as np

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

for BRow in B:
    for ARow in A:
        if all(item in ARow for item in BRow):
            print(f'{BRow} in {ARow}')

This doesn't check for duplicates though, eg it accepts [3, 3] in [1, 2, 3]