2

我有一个正方形 NxN 矩阵。这个矩阵通常很大(N 大约 5000),我想聚合这个矩阵的各个部分来制作一个更小的矩阵。

因此,我有一个包含 N 个元素的列表,这些元素表示哪些行/列应该在新矩阵中组合在一起。

为了使算法更容易和更快,我想根据上面的列表对行和列进行排序。

例子:

输入 5x5 矩阵:

row/col |  1 |  2 |  3 |  4 |  5 |
      1 |  5 |  4 |  3 |  2 |  1 |
      2 | 10 |  9 |  8 |  7 |  6 |
      3 | 15 | 14 | 13 | 12 | 11 |
      4 | 20 | 19 | 18 | 17 | 16 |
      5 | 25 | 24 | 23 | 22 | 21 |

需要明确的是:第一行是 [5 4 3 2 1],第一列是 [5, 10, 15, 20, 25]。

包含“标签”的列表表示哪些行和列应在新矩阵中分组在一起:

[2 2 1 3 3]

这意味着新矩阵将是 3x3(我们有 3 个不同的值)。

带有标签的矩阵:

labels             2       1      3
               --------- ---- ---------
      row/col |  1 |  2 |  3 |  4 |  5 |
   2 |      1 |  5 |  4 |  3 |  2 |  1 |
   2 |      2 | 10 |  9 |  8 |  7 |  6 |
   1 |      3 | 15 | 14 | 13 | 12 | 11 |
   3 |      4 | 20 | 19 | 18 | 17 | 16 |
   3 |      5 | 25 | 24 | 23 | 22 | 21 |

预期的排序矩阵:

row/col |  3 | 1 |  2 |  4 |  5 |
      3 | 13 |15 | 14 | 12 | 11 |
      1 |  3 | 5 |  4 |  2 |  1 |
      2 |  8 |10 |  9 |  7 |  6 |
      4 | 18 |20 | 19 | 17 | 16 |
      5 | 23 |25 | 24 | 22 | 21 |

And with this matrix I can easily sum the grouped elements to form a new element in the 3x3 matrix. Note that the third column and row has moved to the front/top, because it has a lower label value (1 versus 2 and 3).

The question: how to sort a matrix in this way with numpy? I've searched other questions and found lexsort, record arrays and other things, but as someone with not a lot of experience with numpy, I found it hard to accomplish the sorting I wanted.

Thanks in advance!

4

1 回答 1

4

numpy allows you to index over an array or list, thus changing order of columns and rows is easy.

I think this is what you are looking for:

>>> a = np.arange(25).reshape(5,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])   

  >>> a[[2,0,1,3,4]] [:,[2,0,1,3,4]]
array([[12, 10, 11, 13, 14],
       [ 2,  0,  1,  3,  4],
       [ 7,  5,  6,  8,  9],
       [17, 15, 16, 18, 19],
       [22, 20, 21, 23, 24]])

As a side-note:

If you wanted to change order of just rows:

>>> a[[2,0,1,3,4]]
array([[10, 11, 12, 13, 14],
       [ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

If you wanted to change order of just columns:

>>> a[:,[2,0,1,3,4]] 
array([[ 2,  0,  1,  3,  4],
       [ 7,  5,  6,  8,  9],
       [12, 10, 11, 13, 14],
       [17, 15, 16, 18, 19],
       [22, 20, 21, 23, 24]])
于 2013-08-31T12:04:54.223 回答