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

ArraysNumpyPythonNan

Arrays Problem Overview


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

Arrays Solutions


Solution 1 - Arrays

a = a[~np.isnan(a)]

Solution 2 - Arrays

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.

Solution 3 - Arrays

I'm not sure whether this is more or less pythonic...

a = [i for i in a if i is not np.nan]

Solution 4 - Arrays

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnalyticsBuilderView Question on Stackoverflow
Solution 1 - ArraysmtrwView Answer on Stackoverflow
Solution 2 - ArraysEzekiel KruglickView Answer on Stackoverflow
Solution 3 - ArraysMichael MaView Answer on Stackoverflow
Solution 4 - ArrayskaoutherView Answer on Stackoverflow