简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM