12

I have a numpy array with dtype=object, and I want to create a boolean array identifying which elements are None. But it looks like None behaves differently...

a = np.array(['Duck','Duck','Duck','Goose',None,1,2,3,1,3,None,4])
print a == 'Duck'
print a == 3
print a == None

which results in

[ True  True  True False False False False False False False False False]
[False False False False False False False  True False  True False False]
False

Is there an "numpythonic" way to get a boolean array of the None elements? I can use

np.array([x is None for x in a])

but this seems like there should be a better way.

2
  • 1
    I definitely would not have expected ndarrays to behave differently for None... good catch! Commented Sep 25, 2014 at 22:38
  • ...especially because of this quote from the NumPy docs: "Each of the arithmetic operations (+, -, *, /, //, %, divmod(), ** or pow(), <<, >>, &, ^, |, ~) and the comparisons (==, <, >, <=, >=, !=) is equivalent to the corresponding universal function (or ufunc for short) in Numpy." I can only assume the np.equal is the ufunc for ==. Commented Sep 25, 2014 at 22:44

1 Answer 1

13

You can use numpy.equal:

In [20]: np.equal(a, None)
Out[20]: 
array([False, False, False, False,  True, False, False, False, False,
       False,  True, False], dtype=bool)
Sign up to request clarification or add additional context in comments.

4 Comments

This is definately a good workaround, but do you know why it doesn't work for None? The numpy docs say that == should match it's ufunc equivalent, and I imagine the equal is the matching ufunc.
Awesome... I guess that solves the why (it's a bug). Thanks!
Comparison with == None should give a FutureWarning: comparison to 'None' will result in an elementwise object comparison in the future. in current version. None is the only exception where this happens, but that will get fixed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.