3

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?

3
  • 1
    l.sort() does the trick for normal lists Commented Jan 21, 2015 at 18:10
  • Doesn't seem to be doing it. Going l.sort() turns [[2,1], [0,2]] into [[1,2], [0,2]] instead of [[0,2], [2,1]] (when it's an ndarray). Commented Jan 21, 2015 at 18:27
  • l.sort() converts l = [[2,1], [0,2]] into [[0, 2], [2, 1]] only for a normal list and not for an numpy array Commented Jan 21, 2015 at 18:31

1 Answer 1

5

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]])
Sign up to request clarification or add additional context in comments.

3 Comments

Do you know what the time complexity of this is?
@PedroCarvalho: For an h-by-w array, the worst case performance is O(h*w*log(h)), since it's a comparison sort on an input of length h where comparisons can take worst-case O(w) time. If rows usually differ in the first few columns, the expected performance will be O(h*log(h)), since comparisons will take expected O(1) time.
Also, rather than listing columns individually, you can do x[np.lexsort(x.T[::-1])]. (That's still way too many intermediate steps to just do a lexicographic sort, though. NumPy's sorting API seems to be put together in a really weird way.)

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.