Reputation: 322
I am trying to find all None elements in an array using np.where. This is my code:
a = np.array([None, 1, 2, None, 3])
print(np.where(a is None)[0])
print(np.where(a == None)[0])
Oddly, using "a is None" returns an empty array, while using "a==None" returns the correct result. I wonder why this is happening? Thanks!
Update: If a is a python list, then both will behave the same and return []. The difference will only happen when a is cast to an ndarray.
Upvotes: 0
Views: 782
Reputation: 12397
a is None
checks whether a
itself is None
, and does NOT check the elements of a
against None
. In other words, a
is None
if a
itself is None
. So, a is None
returns False
here since a
is not empty. Now, np.where(a is None)
is equivalent to np.where(False)
which is empty and hence its first element is empty as well, returning []
.
On the other hand a == None
checks elements of a
against None
and will return array([ True, False, False, True, False])
which results in the output you see.
In short:
a is None
#False
a == None
#array([ True, False, False, True, False])
Upvotes: 2