2

I want to sort the following matrix by row values:

a = array([[1, 4, 6],
           [5, 3, 7],
           [8, 4, 1]])

as

a = array([[6, 4, 1],
           [7, 5, 3],
           [8, 4, 1]])

I'm able to get the sorting indices using np.argsort(-a) which returns the following matrix of indices:

>>> a_idx = np.argsort(-a)
array([[2, 1, 0],
       [2, 0, 1],
       [0, 1, 2]])

but using these indices to rearrange the original matrix is not happening for me.

>>> a[a_idx]
array([[[8, 4, 1],
        [5, 3, 7],
        [1, 4, 6]],

       [[8, 4, 1],
        [1, 4, 6],
        [5, 3, 7]],

       [[1, 4, 6],
        [5, 3, 7],
        [8, 4, 1]]])

How to efficiently accomplish such a task? Thanks a lot in advance.

2 Answers 2

4

Try this, using .take_along_axis() method,

>>> a = np.array([[1, 4, 6],
                  [5, 3, 7],
                  [8, 4, 1]])   
>>> a_idx = np.argsort(-a)

Output:

>>> np.take_along_axis(a, a_idx, axis=1)        
array([[6, 4, 1],
       [7, 5, 3],
       [8, 4, 1]])
Sign up to request clarification or add additional context in comments.

Comments

2

Another method

import numpy as np
a = np.array([[1, 4, 6],
           [5, 3, 7],
           [8, 4, 1]])
print(np.sort(-a,axis=1)*-1)

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.