Python 如何使用numpy按降序排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36265930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:39:28  来源:igfitidea点击:

How to sort in descending order with numpy?

pythonsortingnumpy

提问by Ribz

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 argsortfunction from numpy that would reverse the order of sorting. But, apparently there is no such argument! Why!?

但这给了我升序排序。此外,在我花了一些时间在互联网上寻找解决方案之后,我希望一定有一个参数可以使argsortnumpy 的功能颠倒排序。但是,显然没有这样的论点!为什么!?

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

有一种说法叫做order。我通过猜测尝试过,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 数组进行排序?

回答by Swier

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