2

Lets say I have a numpy 2D array like this:

a = np.array([[3,6,7],[1,9,4],[ 3,7,8],[2,5,10]])
a
# array([[ 3,  6,  7],
#       [ 1,  9,  4],
#       [ 3,  7,  8],
#       [ 2,  5, 10]])

I need to sort the rows descending based on the first column and ascending on the second column to get the below result:

array([[ 3,  6,  7],
       [ 3,  7,  8],
       [ 2,  5,  10],
       [ 1,  9, 4]])

Doing this in Matlab was simple using sortrows(my_matrix,[-1 2]) where -1 for the first column descending and 2 for the second column ascending.

I wonder if there is a function like that in numpy.

Mahdi
  • 3,188
  • 2
  • 20
  • 33
Hisham Ragheb
  • 144
  • 2
  • 10
  • Inspired by this question I added an example to the `duplicate` that applies `lexsort` to the 1st 2 columns. – hpaulj Aug 07 '16 at 16:36
  • http://stackoverflow.com/questions/2828059/sorting-arrays-in-numpy-by-column Is the suggested duplicate. But seems there's interest in looking at what's different here. – hpaulj Aug 08 '16 at 01:43

2 Answers2

1

If you're willing to use pandas, you can pass a list into the ascending keyword to control the sort order of each field:

>>> pd.DataFrame(a).sort_values([0,1], ascending=[False, True])

   0  1   2
0  3  6   7
2  2  5  10
1  1  9   4
maxymoo
  • 35,286
  • 11
  • 92
  • 119
1

Here is how you can do it using the numpy_indexed package:

import numpy_indexed as npi
print(a[npi.argsort((a[:,1], -a[:,0]))])
Eelco Hoogendoorn
  • 10,459
  • 1
  • 44
  • 42