Sorting arrays in NumPy ascending on one column and descending on other column

Viewed 158

How can I sort 2d array in NumPy by the 1st column ascending and 2nd column descending?

For example,

a = array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5],
           [7, 1, 6]])

Result :

array([[4, 5, 6],
       [7, 1, 6],
       [7, 0, 5],
       [9, 2, 3]])
1 Answers

You can use the np.lexsort function for this

import numpy as np
a = np.asarray([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5],
           [7, 1, 6]])

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

Output

array([[4, 5, 6],
       [7, 1, 6],
       [7, 0, 5],
       [9, 2, 3]])
Related