5

I have an array e.g.

a = [5,1,3,0,2]

I apply the where function:

np.where(a == 2)

The output is an empty array

(array([], dtype=int64),)

I found kind of the same problem here, but in my case it really dosen't make any sense or dose it?

Btw. i'm on a Mac using Python 2.7.10

3
  • 5
    a is a list, not a numpy array. Commented Jan 21, 2018 at 16:39
  • What's your expected output? Commented Jan 21, 2018 at 17:20
  • The interpreter first evaluates a==2, and then passes the result to the where function. Does that a==2 make sense? Commented Jan 21, 2018 at 17:41

1 Answer 1

13

You're passing a list to where() function not a Numpy array. Use an array instead:

In [20]: a = np.array([5,1,3,0,2])

In [21]: np.where(a == 2)
Out[21]: (array([4]),)

Also as mentioned in comments, in this case the value of a == 2 is False, and this is the value passed to where. If a is a numpy array, then the value of a == 2 is a numpy array of bools, and the where function will give you the desire results.

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, the function is not being applied to a list. The value of a == 2 in the question is simply False, and this is the value passed to where. But you are correct in that the problem is that a is a list and not a numpy array. If a is a numpy array, then the value of a == 2 is a numpy array of bools, and then where works as expected.
@WarrenWeckesser Indeed! thanks for point that out, it could cause a miss understanding.
Ah ok now I understand! Thank you very much for your quick and well explained help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.