NumPy - argsort() function
The NumPy argsort() function returns the indices that would sort an array.
Syntax
numpy.argsort(a, axis=-1, kind=None, order=None)
Parameters
a |
Required. Specify the array (array_like) to be sorted. |
axis |
Optional. Specify the axis along which to sort. If None, the array is flattened before sorting. Default is -1, which sorts along the last axis. |
kind |
Optional. Specify sorting algorithm. It can take values from {'quicksort', 'mergesort', 'heapsort', 'stable'}. Default: 'quicksort' |
order |
Optional. Specify string or list of strings containing fields. When a is an array with fields defined, this argument specifies the order in which the fields need to the compared. |
Return Value
Returns an array of indices that sort a along the specified axis. If a is one-dimensional, a[index_array] yields a sorted a. In more general, np.take_along_axis(a, index_array, axis=axis) always yields the sorted a, irrespective of dimensionality.
Example:
In the example below, argsort() function is used to get the indices which is further used to yield the sorted array.
import numpy as np Arr = np.array([50, 40, 10, 60, 30, 20]) #displaying the array print("The original array:") print(Arr) #getting the indices from argsort() x = np.argsort(Arr) print("\nIndices from argsort():") print(x) #yielding sorted array print("\nSorted array:") print(Arr[x])
The output of the above code will be:
The original array: [50 40 10 60 30 20] Indices from argsort(): [2 5 4 1 0 3] Sorted array: [10 20 30 40 50 60]
Example: using axis parameter
The axis parameter can be used to get the indices that will sort the array along given axis, as shown in the example below:
import numpy as np Arr = np.array([[40,10], [20,50]]) #displaying the array print("The original array:") print(Arr) #yielding sorted array along axis=0 x = np.argsort(Arr, axis=0) print("\nSorted array along axis=0:") print(np.take_along_axis(Arr, x, axis=0)) #yielding sorted array along axis=1 y = np.argsort(Arr, axis=1) print("\nSorted array along axis=1:") print(np.take_along_axis(Arr, y, axis=1))
The output of the above code will be:
The original array: [[40 10] [20 50]] Sorted array along axis=0: [[20 10] [40 50]] Sorted array along axis=1: [[10 40] [20 50]]
Example: using order parameter
The order parameter can be used to specify which field need to sort first. Consider the example below:
import numpy as np Arr = np.array([(20,60), (20,50), (20,55), (10,75), (10,25), (10,50)], dtype=[('x', '<i4'), ('y', '<i4')]) #displaying the array print("The original array:") print(Arr) #yielding sorted array indices = np.argsort(Arr, order=('x','y') ) print("\nSorted array:") print(Arr[indices])
The output of the above code will be:
The original array: [(20, 60) (20, 50) (20, 55) (10, 75) (10, 25) (10, 50)] Sorted array: [(10, 25) (10, 50) (10, 75) (20, 50) (20, 55) (20, 60)]
❮ NumPy - Functions