Benoit Hugonnard
Benoit Hugonnard

Reputation: 73

Get an index of a sorted matrix

I have a 2D np.array:

array([[ 1523.,   172.,  1613.],
       [ 3216.,   117.,  1999.],
       [   85.,  1271.,     4.]])

I would to extract the sorted indexes of this np.array by value.
The results should be (for example) : [[2,2],[2,0],[1,1],[0,1],[2,1],[0,0],[0,2],[1,2],[1,0]]

I already saw how to extract the min :

np.unravel_index(np.argmin(act),act.shape) #(2,2)

Thank you

Upvotes: 2

Views: 153

Answers (1)

falsetru
falsetru

Reputation: 368954

Using numpy.argsort with axis=None (assuming flatten array):

>>> import numpy as np
>>> 
>>> act = np.array([[ 1523.,   172.,  1613.],
...                 [ 3216.,   117.,  1999.],
...                 [   85.,  1271.,     4.]])
>>> n = act.shape[1]
>>> zip(*np.argsort(act, axis=None).__divmod__(n))
[(2, 2), (2, 0), (1, 1), (0, 1), (2, 1), (0, 0), (0, 2), (1, 2), (1, 0)]

Upvotes: 2

Related Questions