Search code examples
pythonarrayscomparison

Python: comparing numpy array with sub-numpy array without loop


My problem is quite simple but I cannot figure how to solve it without a loop.

I have a first numpy array:

FullArray = np.array([0,1,2,3,4,5,6,7,8,9])

and a sub array (not necessarily ordered in the same way):

Sub array = np.array([8, 3, 5])

I would like to create a bool array that has the same size of the full array and that returns True if a given value of FullArray is present in the SubArray and False either way.

For example here I expect to get:

BoolArray = np.array([False, False, False, True, False, True, False, False, True, False])

Is there a way to do this without using a loop?


Solution

  • You can use np.isin:

    np.isin(FullArray, SubArray)
    # array([False, False, False, True, False, True, False, False, True, False])