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.
A boolean array can be created manually by using dtype=bool when creating the array. Values other than 0 , None , False or empty strings are considered True. Alternatively, numpy automatically creates a boolean array when comparisons are made between arrays and scalars or between arrays of the same shape.
To compare each element of a NumPy array arr against the scalar x using any of the greater (>), greater equal (>=), smaller (<), smaller equal (<=), or equal (==) operators, use the broadcasting feature with the array as one operand and the scalar as another operand.
NumPy also permits the use of a boolean-valued array as an index, to perform advanced indexing on an array. In its simplest form, this is an extremely intuitive and elegant method for selecting contents from an array based on logical conditions.
Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With