efficient way of removing None's from numpy array

In [17]: a[a != np.array(None)]
Out[17]: array([1, 45, 23, 23, 1234, 3432, -1232, -34, 233], dtype=object)

The above works because a != np.array(None) is a boolean array which maps out non-None values:

In [20]: a != np.array(None)
Out[20]: array([ True,  True,  True,  True,  True,  True,  True,  True,  True, False], dtype=bool)

Selecting elements of an array in this manner is called boolean array indexing.


I use the following which I find simpler than the accepted answer:

a = a[a != None]

Caveat: PEP8 warns against using the equality operator with singletons such as None. I didn't know about this when I posted this answer. That said, for numpy arrays I find this too Pythonic and pretty to not use. See discussion in comments.

Tags:

Python

Numpy