1

I'd like to progressively sort an array, like I can in excel. For example:

randomMatrix = np.asarray(
[[0, 1, 0, 1, 0, 0, 2, 0, 1, 0],
[1, 0, 0, 0, 0, 1, 0, 0, 1, 2],
[1, 1, 0, 0, 2, 0, 0, 1, 0, 0]])

I'd like to have a: "Sort by column 1. Then, sort by column2. Then sort by column3, etc. etc." like we can in excel to produce the following:

sortedMatrix = np.asarray(
[[0, 1, 2, 0, 1, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 2, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 2]])

How can I accomplish this? This answer recommends using lexsort, but when I do I get:

randomMatrix[np.lexsort(randomMatrix.T[::-1])]
array([[0, 1, 0, 1, 0, 0, 2, 0, 1, 0],
       [1, 0, 0, 0, 0, 1, 0, 0, 1, 2],
       [1, 1, 0, 0, 2, 0, 0, 1, 0, 0]])
user79950
  • 259
  • 3
  • 11
  • I can't quite understand what you're sorting. You don't have "an array", you have 3 of them. And if you're sorting the lines as a whole, you cannot rearrange elements in them. – ivan_pozdeev Jan 23 '17 at 20:13

1 Answers1

2

You are sorting by rows which is different from the answer, which is sorting by column, a little adaptation of the answer should work for you:

randomMatrix[:, np.lexsort(randomMatrix)]      # no need to transpose here but the sorting 
                                               # index has to be applied to the second axis

# array([[0, 1, 2, 0, 1, 0, 0, 1, 0, 0],
#        [0, 0, 0, 1, 1, 2, 0, 0, 1, 0],
#        [0, 0, 0, 0, 0, 0, 1, 1, 1, 2]])

Also from the documentation:

If a 2D array is provided for the keys argument, it's rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc.

So here the last row will be the primary sorting key, the second row will be the secondary sorting key and the first row will be the last sorting key. And when actually doing sorting process, with a stable sorting algorithm, the sorting process will be executed on the first row firstly, then the second row and the primary sorting key will be sorted at the final stage. Combined together, np.lexsort returns an integer indices which gives the sorting order. Applying this sorting order to all the rows of your matrix gives the desired output.

Psidom
  • 209,562
  • 33
  • 339
  • 356