简体   繁体   中英

Elementwise comparison to None with ndarray of object dtype

x = np.empty([2], dtype=object)
> array([None, None], dtype=object)

x[0] = 'a'
> array(['a', None], dtype=object)

I'm trying to get a boolean array [False, True] from this object typed ndarray where the object type is None .

Things that don't work: x is None , x.isfinite() , x == None , np.isnan(x) . The array may be in n dimensions, making for loop iterations unpleasant to look at.

In NumPy 1.12 and earlier, you'll need to explicitly call numpy.equal to get a broadcasted equality comparison. Leave a comment, so future readers understand why you're doing it:

# Comparisons to None with == don't broadcast (yet, as of NumPy 1.12).
# We need to use numpy.equal explicitly.
numpy.equal(x, None)

In NumPy 1.13 and later, x == None will give you a broadcasted equality comparison , but you can still use numpy.equal(x, None) if you want backward compatibility with earlier versions.

You can wrap None in a list or array to force element-wise comparisons:

>>> x == [None]
array([False,  True], dtype=bool)

>>> x == np.array([None])
array([False,  True], dtype=bool)

A few possible ways to do that is -

x < 0
x!='a'

array([ True, False], dtype=bool)

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