How to Use the Numpy argsort() Function in Python



In this article, you will learn how to use the Numpy argsort() function in Python.

Numpy argsort() Function

The NumPy argsort() function is a powerful tool in Python for sorting an array and returning the indices that would sort the array. Here’s how you can use the argsort() function in Python:

Import the NumPy library:

import numpy as np

Create an array to sort:

arr = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3])

Use the argsort() function to sort the array and return the indices of the sorted elements:

indices = np.argsort(arr)

This will give you an array of indices that would sort the original array:

array([1, 3, 6, 0, 9, 2, 4, 7, 8, 5], dtype=int64)

You can then use these indices to sort the original array or another array in the same way:

sorted_arr = arr[indices]

This will give you the sorted array:

array([1, 1, 2, 3, 3, 4, 5, 5, 6, 9])

Alternatively, you can sort an array in reverse order by specifying the kind parameter:

indices = np.argsort(arr)[::-1]

This will return an array of indices that would sort the original array in descending order.