如何用numpy降序排序? [英] How to sort in descending order with numpy?

查看:4392
本文介绍了如何用numpy降序排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的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]])

我做了以下事情:

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

但这给了我升序排序.另外,在花了一些时间在Internet上寻找解决方案之后,我期望numpy中必须有一个argsort函数的参数,该参数将颠倒排序顺序.但是,显然没有这样的论点!为什么!?

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!?

有一个名为order的参数.我通过猜测尝试了numpy.argsort(..., order=reverse),但是它不起作用.

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]

由于某些原因,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.

如何按降序对numpy数组排序?

How can I sort a numpy array in descending order?

推荐答案

只需将矩阵乘以-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]]

这篇关于如何用numpy降序排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆