Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse sort of Numpy array with NaN values

I have a numpy array with some NaN values:

>>> a
array([  1.,  -1.,   nan,  0.,  nan], dtype=float32)

I can sort it in ascending or 'descending' order:

>>> numpy.sort(a)
array([ -1.,   0.,   1.,  nan,  nan], dtype=float32)
>>> numpy.sort(a)[::-1]
array([ nan,  nan,   1.,   0.,  -1.], dtype=float32)

However, what I want is descending order with NaN values at the end, like this:

>>> numpy.genuine_reverse_sort(a)
array([ 1.,   0.,   -1.,  nan,  nan], dtype=float32)

How could this be accomplished? I suspect that there is no special method for this.

like image 987
Roman Avatar asked Jan 27 '16 13:01

Roman


People also ask

How do I reverse sort an array in NumPy?

Using flip() function to Reverse a Numpy array The numpy. flip() function reverses the order of array elements along the specified axis, preserving the shape of the array.

How do I get rid of NaN NumPy?

Droping the missing values or nan values can be done by using the function "numpy. isnan()" it will give us the indexes which are having nan values and when combined with other function which is "numpy. logical_not()" where the boolean values will be reversed.

How can I get NaN values in NumPy?

To test array for NaN, use the numpy. isnan() method in Python Numpy. Returns True where x is NaN, false otherwise. This is a scalar if x is a scalar.

Does NumPy mean ignore NaN?

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. axis: we can use axis=1 means row wise or axis=0 means column wise.


1 Answers

What about negating the values twice:

>>> a = np.array([2., -1., nan,  0., nan])
>>> np.sort(a)
array([ -1.,   0.,   2.,  nan,  nan])
>>> -np.sort(-a)
array([  2.,   0.,  -1.,  nan,  nan])
like image 133
Finn Årup Nielsen Avatar answered Sep 28 '22 02:09

Finn Årup Nielsen