Search code examples
pythonsortingnumpylexicographic

Lexicographic sort float array python


Okay, so, I have a 4x2 numpy ndarray, and I want to sort it lexicographically. That is, if I have the array

[[0,0],
[1,1],
[0,1],
[1,0]]

I want it to become

[[0,0],
[0,1],
[1,0],
[1,1]]

How do I do this?


Solution

  • You can use numpy's lexsort. Lexsort, though, sorts using the last column as the primary key. One way to get what you want is to specify the columns explicitly:

     x[np.lexsort((x[:,1], x[:,0]))]
    
     # array([[0, 0],
     #   [0, 1],
     #   [1, 0],
     #   [1, 1]])