简体   繁体   中英

Why does numpy.where behave differently for “== None” and “is None” when trying to find None elements in array?

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.

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM