Find NumPy Array Strings That Contain Any List

I have a 2D NumPy array aand a list / set / 1D NumPy array b. I would like to find those lines athat contain any of b, i.e.

import numpy as np

a = np.array([
    [1, 2, 3],
    [4, 5, 3],
    [0, 1, 0]
    ])

b = np.array([1, 2])

# result: [True, False, True]

Any clues?

+4
source share
1 answer

You can use np.in1dto find matches for any item from bin each item in a. Now it np.in1dwill smooth arrays, so we will need to change the shape later. Finally, since we want to search ANYfor each line in a, use np.anyalong each line. So we would have an implementation like this:

np.in1d(a,b).reshape(a.shape).any(axis=1)
+5

Source: https://habr.com/ru/post/1648507/


All Articles