Thursday, September 25, 2025
HomeLanguagesHow to get the indices of the sorted array using NumPy in...

How to get the indices of the sorted array using NumPy in Python?

We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that would sort the array.

Syntax:

numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None)

Example 1:

Python3




import numpy as np
 
 
# Original array
array = np.array([10, 52, 62, 16, 16, 54, 453])
print(array)
 
# Indices of the sorted elements of a
# given array
indices = np.argsort(array)
print(indices)


Output:

[ 10  52  62  16  16  54 453]
[0 3 4 1 5 2 6]

Example 2:

Python3




import numpy as np
 
 
# Original array
array = np.array([1, 2, 3, 4, 5])
print(array)
 
# Indices of the sorted elements of
# a given array
indices = np.argsort(array)
print(indices)


Output:

[1 2 3 4 5]
[0 1 2 3 4]

Example 3:

Python3




import numpy as np
 
 
# input 2d array
in_arr = np.array([[ 2, 0, 1], [ 5, 4, 3]])
print ("Input array :\n", in_arr) 
   
# output sorted array indices
out_arr1 = np.argsort(in_arr, kind ='mergesort', axis = 0)
print ("\nOutput sorted array indices along axis 0:\n", out_arr1)
 
out_arr2 = np.argsort(in_arr, kind ='heapsort', axis = 1)
print ("\nOutput sorted array indices along axis 1:\n", out_arr2)


Output:

Input array :
 [[2 0 1]
 [5 4 3]]

Output sorted array indices along axis 0:
 [[0 0 0]
 [1 1 1]]

Output sorted array indices along axis 1:
 [[1 2 0]
 [2 1 0]]
RELATED ARTICLES

Most Popular

Dominic
32319 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6682 POSTS0 COMMENTS
Nicole Veronica
11854 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11910 POSTS0 COMMENTS
Shaida Kate Naidoo
6795 POSTS0 COMMENTS
Ted Musemwa
7071 POSTS0 COMMENTS
Thapelo Manthata
6753 POSTS0 COMMENTS
Umr Jansen
6761 POSTS0 COMMENTS