Ralph
Ralph

Reputation:

Sorting an array based on one column, then based on a second column

I would like sort an array based on one column, then for all the columns values that are equal - sort them based on a second column. For example: suppose that I have the array:

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

I can sort it by column 0 using:

sorted_array = a[np.argsort(a[:, 0])]

however, I want rows that have similar values at the [0] column to be sorted by the [1] column, so my result would look like:

desired_result = np.array([[0,1,1],[0,2,1],[0,3,1],[1,7,2]])

What is the best way to achieve that? Thanks.

Upvotes: 0

Views: 769

Answers (2)

Bob
Bob

Reputation: 14654

You first sort the array in the secondary column, then you sort in the primary axis, making sure to use a stable sorting method.

sorted_array = a[np.argsort(a[:, 1])]
sorted_array = sorted_array[np.argsort(sorted_array[:, 0], kind='stable')]

Or you can use lexsort

sorted_array = a[np.lexsort((a[:,1], a[:, 0])), :]

Upvotes: 0

Quang Hoang
Quang Hoang

Reputation: 150735

You can sort them as tuple, then convert back to numpy array:

out = np.array(sorted(map(tuple,a)))

Output:

array([[0, 1, 1],
       [0, 2, 1],
       [0, 3, 1],
       [1, 7, 2]])

Upvotes: 1

Related Questions