8

I have a list

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

which I have made into an array using numpy.array:

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

How do I sort this like a table? In particular, I want to sort by the second column in ascending order and then resolve any ties by having the first column sorted in ascending order. Thus I desire:

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

Any help would be greatly appreciated!

4 Answers 4

9

See http://docs.scipy.org/doc/numpy/reference/generated/numpy.lexsort.html#numpy.lexsort

Specifically in your case,

import numpy as np
x = np.array([[0,3],[5,1],[2,1],[4,5]])
x[np.lexsort((x[:,0],x[:,1]))]

outputs

array([[2,1],[5,1],[0,3],[4,5]])
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for the solution. I like this the best because it shows me that by replacing x[:,0] with x[::-1,0], I am able to reverse the direction of the second sorting (of the first column). Many thanks all!
4

You can use numpy.lexsort():

>>> a = numpy.array([[0, 3], [5, 1], [2, 1], [4, 5]])
>>> a[numpy.lexsort(a.T)]
array([[2, 1],
       [5, 1],
       [0, 3],
       [4, 5]])

Comments

2

Another way of doing this - slice out the bits of data you want, get the sort indices using argsort, then use the result of that to slice your original array:

a = np.array([[0, 3], [5, 1], [2, 1], [4, 5]])

subarray = a[:,1] # 3,1,1,5

indices = np.argsort(subarray) # Returns array([1,2,0,3])

result = a[indices]

Or, all in one go:

a[np.argsort(a[:,1])]

2 Comments

This doesn't sort the ties necessarily (1st column in ascending order).
True - lexsort looks like a better option here
1

If you want to sort using a single column only (e.g., second column), you can do something like:

from operator import itemgetter
a = [[0, 3], [5, 1], [2, 1], [4, 5]]
a_sorted = sorted(a, key=itemgetter(1))

If there are more than one key, then use numpy.lexsort() as pointed out in the other answers.

1 Comment

Thank you, for my case numpy.array(sorted(a, key=itemgetter(1))) worked perfectly still being the most readable option.

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.