2

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]])
Sudhansu Kumar
  • 129
  • 1
  • 3
  • 10

1 Answers1

4

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]])
Clock Slave
  • 7,627
  • 15
  • 68
  • 109