Let us explore how to work with the NumPy argsort() function.
NumPy argsort() Function Syntax
The function syntax and parameters are as shown in the following:
Parameters
The parameters are defined according to their following functions:
- a – refers to the input array.
- axis – specifies along which axis to sort the input array. The value is set to -1, which uses the last index. Set the axis parameter to None if you want to flatten the array.
- kind – specifies the sorting algorithm. Acceptable values include ‘quicksort’, ‘mergesort’, ‘heapsort’, and ‘stable’. By default, the function will use a quicksort sorting algorithm.
- order – defines the order under which to compare the fields.
Function Return Value
The function returns an array of indices of the sorted array according to the set parameters.
Example 1 – Flattened Array Sort
The following example shows how to flatten and sort the array by specifying the axis parameter as “None”.
import numpy as np
arr = [0,1,5,3,9,6,7,4,2,8]
print("unsorted array: ", arr)
print(f"sorted array: {np.argsort(arr, axis=None)}")
The previous code returns an array with the indices of the sorted array. An example output is as shown below:
sorted array: [0 1 8 3 7 2 5 6 9 4]
Example 2 – Flattened Array Sort (Different Algorithms)
Consider the example below that shows how to sort a flattened array using various sorting algorithms:
quick_sort = np.argsort(arr, axis=None, kind='quicksort')
merge_sort = np.argsort(arr, axis=None, kind='mergesort')
heap_sort = np.argsort(arr, axis=None, kind='heapsort')
stable = np.argsort(arr, axis=None, kind='heapsort')
print(f" quicksort: {quick_sort}\n mergesort: {merge_sort}\n heapsort: {heap_sort}\n stable: {stable}")
The previous code utilizes various sorting algorithms and returns the resulting array indices.
The following is an output example:
mergesort: [0 1 8 3 7 2 5 6 9 4]
heapsort: [0 1 8 3 7 2 5 6 9 4]
stable: [0 1 8 3 7 2 5 6 9 4]
Example 3 – Sort 2D Array Along Various Axis
Let’s look at an example in sorting a 2D array along the various axis.
The return array is as follows:
[0 0 0]]
To sort along axis 1, apply the following code:
This should return to:
[2 1 0]]
Conclusion
This article serves as a guide on how to use the argsort() function in NumPy to sort an array along a specific axis using various algorithms. More tutorials are available at Linux Hint.