我有一个正方形 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!