ahajib
ahajib

Reputation: 13510

Python numpy keep a list of indices of a sorted 2D array

I have a 2D numpy array and I want to create a new 1D array where it is indices of numbers in the first array if they are sorted in an ascending order. For the following array:

A = [[1,0,2],
     [0,3,0]]

I want this to be like:

B = [[1,1],[0,2],[0,0],[0,1],[1,0],[1,2]]

Any idea how it can be done in python using predefined functions?

Thanks

Upvotes: 9

Views: 2793

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77991

You can use argsort to sort the indices of flattened array, followed by unravel_index to convert the flat index back to coordinates:

>>> i = (-a).argsort(axis=None, kind='mergesort')
>>> j = np.unravel_index(i, a.shape) 
>>> np.vstack(j).T
array([[1, 1],
       [0, 2],
       [0, 0],
       [0, 1],
       [1, 0],
       [1, 2]])

-a and kind='mergesort' is in order to sort the array in a stable manner in descending order (to match the output you are looking for).

If you do not care about having a stable sort, replace the first line with:

>>> i = a.argsort(axis=None)[::-1]

Upvotes: 13

Related Questions