[英]How to sort in descending order with numpy?
I have a numpy array like this: 我有一个像这样的numpy数组:
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. 此外,在我花了一些时间在互联网上寻找解决方案后,我希望numpy中的
argsort
函数必须有一个参数可以反转排序顺序。 But, apparently there is no such argument! 但是,显然没有这样的论点! Why!?
为什么!?
There is an argument called order
. 有一个称为
order
的论证。 I tried, by guessing, numpy.argsort(..., order=reverse)
but it does not work. 我试过,通过猜测,
numpy.argsort(..., order=reverse)
但它不起作用。
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. 由于某种原因,
As = As[::-1]
没有给我所需的输出。
Well, I guess it must be simple but I am missing something. 好吧,我想这一定很简单,但我错过了一些东西。
How can I sort a numpy array in descending order? 如何按降序对numpy数组进行排序?
Just multiply your matrix by -1 to reverse order: 只需将矩阵乘以-1即可逆序:
[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]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.