Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a boolean array which compares numpy elements to None

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.

like image 760
Jason S Avatar asked Sep 25 '14 22:09

Jason S


People also ask

How do you make a boolean NumPy array?

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.

How do I compare all elements in a NumPy array?

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.

Does NumPy arrays support boolean indexing?

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.

How do you compare elements in an array in Python?

Use a comparison operator (==) to form a comparison array. Check if all the elements in the comparison array are True.


1 Answers

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)
like image 173
Ashwini Chaudhary Avatar answered Sep 19 '22 13:09

Ashwini Chaudhary