title: Sort rows and columns of a matrix by another list with numpy
body: <p>I have a square NxN matrix. This matrix is often quite large (N around 5000), and I want to aggregate parts of this matrix to make a smaller matrix. </p>
  
  <p>Therefore, I have a list with N elements, and these elemenets denote which rows/columns should be grouped together in the new matrix. </p>
  
  <p>To make the algorithm a bit easier and faster, I want to sort the rows and columns based on the above list. </p>
  
  <p>Example:</p>
  
  <p>Input 5x5 matrix:</p>
  
  <pre><code>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 |
  </code></pre>
  
  <p>To be clear: the first row is [5 4 3 2 1] and the first column is [5, 10, 15, 20, 25].</p>
  
  <p>The list containing the 'labels' which denote which rows and columns should be grouped together in the new matrix:</p>
  
  <pre><code>[2 2 1 3 3]
  </code></pre>
  
  <p>This means the new matrix will be 3x3 (we have 3 distinct values). </p>
  
  <p>The matrix with the labels:</p>
  
  <pre><code>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 |
  </code></pre>
  
  <p>Expected sorted matrix:</p>
  
  <pre><code>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 |
  </code></pre>
  
  <p>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).</p>
  
  <p>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. </p>
  
  <p>Thanks in advance!</p>