Python

# NumPy np.argsort()

The argsort() function in NumPy allows you to perform an indirect sorting of an array along a specified axis using the set algorithm.

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:

numpy.argsort(a, axis=- 1, kind=None, order=None)

Parameters
The parameters are defined according to their following functions:

1. a – refers to the input array.
2. 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.
3. kind – specifies the sorting algorithm. Acceptable values include ‘quicksort’, ‘mergesort’, ‘heapsort’, and ‘stable’. By default, the function will use a quicksort sorting algorithm.
4. 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
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:

unsorted array:  [0, 1, 5, 3, 9, 6, 7, 4, 2, 8]
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:

arr = [0,1,5,3,9,6,7,4,2,8]
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:

quicksort: [0 1 8 3 7 2 5 6 9 4]
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.

print(f"axis 0: {np.argsort(arr, axis=0)}")

The return array is as follows:

axis 0: [[1 1 1]
[0 0 0]]

To sort along axis 1, apply the following code:

print(f"axis 1: {np.argsort(arr, axis=1)}")