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
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.
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.
NumPy's np. argsort is able to do stable sorting through passing kind = 'stable' argument. Also np. argsort doesn't support reverse (descending) order.
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 .
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With