Sort array by specific column then sort by value of this column

Viewed 26

I'm currently learning Python and I'm trying to sort an array. As the title is problably not very specific I'm gonna give an exemple of what I'm tring to do : I have an array like that :

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

But with much more rows and higher numbers and I would like that :

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

For the moment I managed to obtain this :

a = array([[0, 5], [0, 3], [1, 5], [1, 0]])

by using a = a[a[:, 0].argsort()]

But I'm stuck there and I haven't found help for my problem anywhere and I don't have any idea how to procede...

Could anyone help me please ?

1 Answers

You could use the built-in function sorted:

import numpy as np

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


result = np.array(sorted(a, key=tuple))

print(result)

Output

[[0 3]
 [0 5]
 [1 0]
 [1 2]]
Related