Home > other >  Python "in" keyword-function does not work properly on numpy arrays
Python "in" keyword-function does not work properly on numpy arrays

Time:12-09

Why does this piece of code return True when it clearly can be seen that the element [1, 1] is not present in the first array and what am I supposed to change in order to make it return False?

aux = np.asarray([[0, 1], [1, 2], [1, 3]])
np.asarray([1, 1]) in aux

True

CodePudding user response:

Checking for equality for the two arrays broadcasts the 1d array so the == operator checks if the corresponding indices are equal.

>>> np.array([1, 1]) == aux
array([[False,  True],
       [ True, False],
       [ True, False]])

Since none of the inner arrays are all True, no array in aux is completely equal to the other array. We can check for this using

np.any(np.all(np.array([1, 1]) == aux, axis=1))

CodePudding user response:

You can think of the in operator looping through an iterable and comparing each item for equality with what's being matched. I think what happens here can be demonstrated with the comparison to the first vector in the matrix/list:

>>> np.array([1, 1]) == np.array([0,1])
array([False,  True])

and bool([False, True]) in Python == True so the in operator immediately returns.

  • Related