Last Updated : 11 Jul, 2025
numpy.argsort() is a function in NumPy that returns the indices that would sort an array. In other words, it gives you the indices that you would use to reorder the elements in an array to be in sorted order. Example:
Python
import numpy as np
a = np.array([2, 0, 1, 5, 4, 1, 9])
idx = np.argsort(a)
print("Original array:", a)
print("Indices to sort:", idx)
print("Sorted array:", a[idx])
Original array: [2 0 1 5 4 1 9] Indices to sort: [1 2 5 0 4 3 6] Sorted array: [0 1 1 2 4 5 9]
Explanation: np.argsort(a) returns [1 2 5 0 4 3 6], the indices that would sort a. and a[idx] gives the sorted array.
Syntax
numpy.argsort(arr, axis=-1, kind='quicksort', order=None)
Parameters:
Return: [index_array, ndarray] Array of indices that sort arr along the specified axis. If arr is one-dimensional then arr[index_array] returns a sorted arr.
Examples of numpy.argsort()Example 1: This example demonstrates how to use numpy.argsort() with different axes to return indices that would sort a 2D NumPy array along rows and columns.
Python
import numpy as np
a = np.array([[2, 0, 1], [5, 4, 3]])
print("Axis 0:\n", np.argsort(a, axis=0))
print("Axis 1:\n", np.argsort(a, axis=1))
Axis 0: [[0 0 0] [1 1 1]] Axis 1: [[1 2 0] [2 1 0]]
Explanation:
Example 2: This example finds the indices of the two largest elements in a NumPy array and retrieves their values in descending order.
Python
import numpy as np
x=np.array([12,43,2,100,54,5,68])
print(np.argsort(x))
print(np.argsort(x)[-2:])
print(np.argsort(x)[-2:][::-1])
print(x[np.argsort(x)[-2:][::-1]])
[2 5 0 1 4 6 3] [6 3] [3 6] [100 68]
Explanation:
Example 3: This example assigns ranks to array elements based on their values, with the smallest value ranked 0, the next smallest 1 and so on.
Python
import numpy as np
a = np.array([50, 10, 20, 30])
res = np.argsort(np.argsort(a))
print(res)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4