[Solved] 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?

Enquirer: Ribz

||
Solution #1:

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]]
Respondent: Swier
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.