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
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.
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.
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.
a = a[~np.isnan(a)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With