0

I'm trying to sort a 2d array in numpy by its entire rows: that is, the elements in each row should be kept in their order within that row, but the entire row itself can be swapped with another. For each row, their order is determined by their elements: going through each element, if the ith element in row 1 is the same as row 2, look at the ith + 1 element. Else, take the row whose ith element is smaller. :

import numpy as np
a = array([[1,2,3,4],
           [0,3,4,5],
           [1,2,4,5],
           [0,2,4,5],])

return:

          [[0,2,4,5],
           [0,3,4,5],
           [1,2,3,4],
           [1,2,4,5]]

Is there a prebuilt numpy function that does this?

1 Answer 1

1

There is np.lexsort. Pass in the columns of a (as rows, hence a.T) as the sorting keys, being aware that the last key defines the primary sort order (hence reverse the keys with a.T[::-1]):

>>> a[np.lexsort(a.T[::-1])]
array([[0, 2, 4, 5],
       [0, 3, 4, 5],
       [1, 2, 3, 4],
       [1, 2, 4, 5]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.