Python numpy stores index list of sorted 2d array

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

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

I want it to be like this:

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

Any idea how to do this in python using predefined functions?

thanks

+6
source share
1 answer

You can use argsort to sort the indices of a flattened array, then 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 to sort the array in a stable manner in descending order (according to the query you are looking for).

If you do not need stable sorting, replace the first line as follows:

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

Source: https://habr.com/ru/post/985468/


All Articles