0

I have an array

A = np.array([[   1. ,   -1. ,     0.],
              [  50. ,   10. ,    0.],
              [  10. ,   10. ,    2.],
              [-110. ,   -1. ,     1.],
              [ 120. ,   10. ,     1.],
              [-150. ,   -1. ,     2.]])

which I would like to sort FIRST in descending order based on the second column and THEN in ascending order based on the third column without altering the result from the sorting of the second column. So my result should look like:

array([[  50. ,   10. ,     0.],
       [ 120. ,   10. ,     1.],
       [  10. ,   10. ,     2.],
       [   1. ,   -1. ,     0.],
       [-110. ,   -1. ,     1.],
       [-150. ,   -1. ,     2.]])

This is what I could do best but this alters the sorting done on the second column:

ind = np.lexsort((-A[:,1],A[:,2]))
A = A[ind]

which produces the following:

array([[  50.,   10.,    0.],
       [   1.,   -1.,    0.],
       [ 120.,   10.,    1.],
       [-110.,   -1.,    1.],
       [  10.,   10.,    2.],
       [-150.,   -1.,    2.]])

Your help is highly appreciated. Thank you!

1 Answer 1

1

You can use python's built-in sorted for this:

A = np.array(sorted(A, key=lambda x: (x[1], -x[2]), reverse=True))

By negating the second sorting characteristic (x[2]) and setting reverse to True, it will sort first the second column in descending order, then the third in ascending order.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.