Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 658
David Parks Avatar asked Feb 05 '26 09:02

David Parks


1 Answers

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.

like image 73
user2357112 supports Monica Avatar answered Feb 07 '26 21:02

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!