Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort in descending order with numpy?

I have a numpy array like this:

A = array([[1, 3, 2, 7],
           [2, 4, 1, 3],
           [6, 1, 2, 3]])

I would like to sort the rows of this matrix in descending order and get the arguments of the sorted matrix like this:

As = array([[3, 1, 2, 0],
            [1, 3, 0, 2],
            [0, 3, 2, 1]])

I did the following:

import numpy
A = numpy.array([[1, 3, 2, 7], [2, 4, 1, 3], [6, 1, 2, 3]])
As = numpy.argsort(A, axis=1)

But this gives me the sorting in ascending order. Also, after I spent some time looking for a solution in the internet, I expect that there must be an argument to argsort function from numpy that would reverse the order of sorting. But, apparently there is no such argument! Why!?

There is an argument called order. I tried, by guessing, numpy.argsort(..., order=reverse) but it does not work.

I looked for a solution in previous questions here and I found that I can do:

import numpy
A = numpy.array([[1, 3, 2, 7], [2, 4, 1, 3], [6, 1, 2, 3]])
As = numpy.argsort(A, axis=1)
As = As[::-1]

For some reason, As = As[::-1] does not give me the desired output.

Well, I guess it must be simple but I am missing something.

How can I sort a numpy array in descending order?

like image 447
Ribz Avatar asked Mar 28 '16 15:03

Ribz


People also ask

Does NumPy sort ascending descending?

Answer. In Numpy, the np. sort() function does not allow us to sort an array in descending order. Instead, we can reverse an array utilizing list slicing in Python, after it has been sorted in ascending order.

How do you sort an array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

How do you sort a 2D NumPy array in descending order?

Sort the rows of a 2D array in descending order The code axis = 1 indicates that we'll be sorting the data in the axis-1 direction, and by using the negative sign in front of the array name and the function name, the code will sort the rows in descending order.

How do you put an array in descending order in Python?

Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order.


1 Answers

Just multiply your matrix by -1 to reverse order:

[In]: A = np.array([[1, 3, 2, 7],
                    [2, 4, 1, 3],
                    [6, 1, 2, 3]])
[In]: print( np.argsort(-A) )
[Out]: [[3 1 2 0]
        [1 3 0 2]
        [0 3 2 1]]
like image 142
Swier Avatar answered Oct 03 '22 11:10

Swier