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.

2
  • Inspired by this question I added an example to the duplicate that applies lexsort to the 1st 2 columns. Commented Aug 7, 2016 at 16:36
  • stackoverflow.com/questions/2828059/… Is the suggested duplicate. But seems there's interest in looking at what's different here. Commented Aug 8, 2016 at 1:43

2 Answers 2

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]))])
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.