Wednesday, December 25, 2024
Google search engine
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

Recent Comments