2

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

5
  • 1
    Why not use isin()? Commented Dec 8, 2021 at 18:26
  • 1
    stackoverflow.com/questions/18320624/… Commented Dec 8, 2021 at 18:29
  • 1
    @RandomDavis: Doesn't work. That broadcasts over the left operand. It doesn't mean "is this array in this other array"; it means "for each element of this array, is that element in this other array". Commented Dec 8, 2021 at 18:30
  • 1
    In a deleted comment you say the actual arrays are float. == tests don't work reliably on floats. Giving an int example will probably produce useless answers. Commented Dec 8, 2021 at 18:44
  • You are assuming that in applied to arrays should behave the same as with lists. Use lists if that's what you want. Otherwise, accept the fact that numpy arrays are multidimensional, and implement their own form of in. Generally though, we don't use in with arrays. There are better tools that give more control. Commented Dec 8, 2021 at 21:12

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

And it is quite performant as well. Testing an array with 1e6 lines takes about 0.015 s in my machine (timeit.timeit('np.any(np.all(a == b, axis=1))', setup='import numpy as np; a=np.random.rand(1000000, 2); b=np.asarray([-1,1])', number=10)/10)
-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.