按目标列对numpy矩阵中的所有行进行排序

时间:2016-05-29 22:11:22

标签: python sorting numpy matrix

这似乎被多次询问,但我发现现在的答案不起作用。让我们变得简单,这里我有一个numpy矩阵

$start = 10;
$end = 1;
$find = rand(0,9); 

do { 
    if ($start != $find): // ALWAYS true, can be omitted
        echo $start; 
        $start = $start - $end;
    endif;
} while ($start != $find);

if ($start == $find): // ALWAYS true, can be omitted
    echo "Found!";
endif;

然后按第二列排序,如下所示

data = np.matrix([[9, 8],
             [7, 6],
             [5, 7],
             [3, 2],
             [1, 0]])

我尝试过很多像Python Matrix sorting via one column这样的例子,但都没有。

我想知道可能因为多年前发布的答案不适用于最新的Python?我的Python是3.5.1。

我失败的审判示例:

[[1, 0],
[3, 2],
[7, 6],
[5, 7],
[9, 8]])          

2 个答案:

答案 0 :(得分:4)

你是一个移动的目标。

单独对每列进行排序:

In [151]: np.sort(data,axis=0)
Out[151]: 
matrix([[1, 0],
        [3, 2],
        [5, 6],
        [7, 7],
        [9, 8]])

对第二列的值进行排序

In [160]: ind=np.argsort(data[:,1],axis=0)

In [161]: ind
Out[161]: 
matrix([[4],
        [3],
        [1],
        [2],
        [0]], dtype=int32)

In [162]: data[ind.ravel(),:]  # ravel needed because of matrix
Out[162]: 
matrix([[[1, 0],
         [3, 2],
         [7, 6],
         [5, 7],
         [9, 8]]])

获取有效ind数组的另一种方法:

In [163]: ind=np.argsort(data.A[:,1],axis=0)

In [164]: ind
Out[164]: array([4, 3, 1, 2, 0], dtype=int32)

In [165]: data[ind,:]

要使用lexsort,您需要类似

的内容
In [175]: np.lexsort([data.A[:,0],data.A[:,1]])
Out[175]: array([4, 3, 1, 2, 0], dtype=int32)

或您的失败'案例 - 这不是一个失败

In [178]: np.lexsort((data.A[:,1],))
Out[178]: array([4, 3, 1, 2, 0], dtype=int32)

此处data[:,1]是主键。 data[:,0]是决胜局(在您的示例中不适用)。我只是在文档中工作。

答案 1 :(得分:1)

链接中的方法正在运行:

import numpy as np

data = np.matrix([[9, 8],
         [7, 6],
         [5, 7],
         [3, 2],
         [1, 0]])

print(data[np.argsort(data.A[:, 1])])

[[1 0]
 [3 2]
 [7 6]
 [5 7]
 [9 8]]

现在举一个更好的例子:

data = np.matrix([[1, 9],
         [2, 8],
         [3, 7],
         [4, 6],
         [0, 5]])
[[0 5]
 [4 6]
 [3 7]
 [2 8]
 [1 9]]