Reputation: 2556
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.
Upvotes: 2
Views: 908
Reputation: 5785
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]])
Upvotes: 4
Reputation: 1086
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)
Upvotes: 2