Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
ahajib Avatar asked Apr 19 '15 19:04

ahajib


People also ask

How do I get the indices of a sorted array in NumPy?

We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword.

Can I store a list in a NumPy array?

NumPy arrays are used to store lists of numerical data and to represent vectors, matrices, and even tensors. NumPy arrays are designed to handle large data sets efficiently and with a minimum of fuss. The NumPy library has a large set of routines for creating, manipulating, and transforming NumPy arrays.

Is NumPy Argsort stable?

NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument. Also np. argsort doesn't support reverse (descending) order.

What is NumPy Unravel_index?

numpy. unravel_index(indices, shape, order='C') Converts a flat index or array of flat indices into a tuple of coordinate arrays. Parameters indicesarray_like. An integer array whose elements are indices into the flattened version of an array of dimensions shape .


1 Answers

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]
like image 134
behzad.nouri Avatar answered Sep 29 '22 17:09

behzad.nouri