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?
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.
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.
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.
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.
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]]
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