"isnotnan" functionality in numpy, can this be more pythonic?

Question:

I need a function that returns non-NaN values from an array. Currently I am doing it this way:

>>> a = np.array([np.nan, 1, 2])
>>> a
array([ NaN,   1.,   2.])

>>> np.invert(np.isnan(a))
array([False,  True,  True], dtype=bool)

>>> a[np.invert(np.isnan(a))]
array([ 1.,  2.])

Python: 2.6.4
numpy: 1.3.0

Please share if you know a better way,
Thank you

Asked By: AnalyticsBuilder

||

Answers:

a = a[~np.isnan(a)]
Answered By: mtrw

You are currently testing for anything that is not NaN and mtrw has the right way to do this. If you are interested in testing for finite numbers (is not NaN and is not INF) then you don’t need an inversion and can use:

np.isfinite(a)

More pythonic and native, an easy read, and often when you want to avoid NaN you also want to avoid INF in my experience.

Just thought I’d toss that out there for folks.

Answered By: Ezekiel Kruglick

I’m not sure whether this is more or less pythonic…

a = [i for i in a if i is not np.nan]
Answered By: Michael Ma

To get array([ 1., 2.]) from an array arr = np.array([np.nan, 1, 2])
You can do :

 arr[~np.isnan(arr)]

OR

arr[arr == arr] 

(While : np.nan == np.nan is False)

Answered By: kaouther
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.