根据特定列使用numpy对矩阵进行反向排序

时间:2018-10-23 15:49:00

标签: python sorting numpy matrix

    x <- 10

Some code explanation, next code block hidden here but still evaluated

Some more code explanation

    z <- x + y

The final output

    # 10

Annex 1
=======

Each block individually:

    x <- 10

    y <- 10

    z <- x + y

Annex 2
=======

If you want them more compactly concatenated:

    x <- 10
    y <- 10
    z <- x + y

输出:

import numpy as np

mat = np.array([[1,21,3],[5,4,2],[56,12,4]])
mat_sort = mat[mat[:,2].argsort()]
print(mat_sort)

如果我希望基于任何列(例如3rd)进行反向排序,那么我对该代码进行哪些更改?意思是,我希望得到:

[[ 5  4  2]
 [56 12  4]
 [ 1 21  3]]

P.s是的,我知道这是一个简单的问题,但是我找不到我理解的答案,该答案基于矩阵而不是数组或向量。 TIA:)

2 个答案:

答案 0 :(得分:1)

只需反转argsort索引:

mat_sort = mat[mat[:, 2].argsort()[::-1]]

答案 1 :(得分:1)

print(mat_sort[::-1]) #just print in reverse