Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 859
AnalyticsBuilder Avatar asked May 14 '10 02:05

AnalyticsBuilder


People also ask

What does NumPy Nanmean do?

nanmean() function can be used to calculate the mean of array ignoring the NaN value. If array have NaN value and we can find out the mean without effect of NaN value.

How do you know if a variable is NP NaN?

The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.

Is NumPy always faster than Python?

There is a big difference between the execution time of arrays and lists. NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations.


2 Answers

a = a[~np.isnan(a)] 
like image 144
mtrw Avatar answered Sep 22 '22 08:09

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.

like image 39
Ezekiel Kruglick Avatar answered Sep 21 '22 08:09

Ezekiel Kruglick