Hisham Ragheb
Hisham Ragheb

Reputation: 144

How to sort a numpy 2D array rows descending or ascending using a specific column indices

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.

Upvotes: 2

Views: 1203

Answers (2)

Eelco Hoogendoorn
Eelco Hoogendoorn

Reputation: 10759

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]))])

Upvotes: 1

maxymoo
maxymoo

Reputation: 36545

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

Upvotes: 1

Related Questions