9

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

1 Answer 1

13

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]
Sign up to request clarification or add additional context in comments.

3 Comments

The tip about using np.unravel_index is brilliant! I am glad to learn this method.
What do you mean by "stable sort"? Does this produce consistent sorting for identical values?
@stvn66 I believe this does produce consistent sorting for identical values which is equal to stable sorting

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.