The NumPy module provides a function argsort(), returns the indices which would sort an array.
The NumPy module provides a function for performing an indirect sort along with the given axis with the help of the algorithm specified by the keyword. This function returns an array of indices of the same shape as 'a', which would sort the array.
numpy.argsort(a, axis=-1, kind=None, order=None)
These are the following parameters in numpy.argsort() function:
a: array_like
This parameter defines the source array which we want to sort.
axis: int or None(optional)
This parameter defines the axis along which the sorting is performed. By default, the axis is -1. If we set this parameter to None, the flattened array is used.
kind: {'quicksort','mergesort','heapsort','stable'}(optional)
This parameter defines the sorting algorithm. By default, the algorithm is quicksort. Both mergesort and stable are using time sort under the covers. The actual implementation will vary with the data type. The mergesort option is retained for backward compatibility.
order: str or list of str(optional)
If 'a' is an array with defined fields, this argument specifies which fields to compare first, second, etc. The single field can be specified as a string, and not all fields need to be specified. But unspecified fields will still use, in the order in which they come up in the dtype, to break the ties.
This function returns an array of indices which sort 'a' along with the specified axis. If 'a' is 1-D, a[index_array] yields a sorted 'a'. More generally, np.take_along_axis(arr1, index_array, axis=axis) always yields the sorted 'a', irrespective of dimensionality.
import numpy as np a=np.array([456,11,63]) a b=np.argsort(a) b
In the above code
In the output, a ndarray has been shown that contains the indices(indicate the position of the element for the sorted array) and dtype.
Output:
import numpy as np a = np.array([[0, 5], [3, 2]]) indices = np.argsort(a, axis=0) indices
Output:
import numpy as np a = np.array([[0, 5], [3, 2]]) indices = np.argsort(a, axis=0) indices np.take_along_axis(a, indices, axis=0)
In the above code
In the output, a 2-D array with sorted elements has been shown.
Output:
import numpy as np a = np.array([[0, 5], [3, 2]]) indices = np.argsort(a, axis=1) indices
Output:
import numpy as np a = np.array([[0, 5], [3, 2]]) indices = np.argsort(a, axis=1) indices np.take_along_axis(a, indices, axis=1)
Output:
import numpy as np a = np.array([[0, 5], [3, 2]]) indices = np.unravel_index(np.argsort(a, axis=None), a.shape) indices a[indices] # same as np.sort(a, axis=None)
Output:
In the above code
In the output, an N-D array with sorted elements has been shown.
import numpy as np a= np.array([(0, 5), (3, 2)], dtype=[('x', '<i4'), ('y', '<i4')]) a b=np.argsort(a, order=('x','y')) b c=np.argsort(a, order=('y','x')) c
Output:
In the above code
In the output, a sorted array has been shown with dtype=[('x', '<i4'), ('y', '<i4')]