w3resource

NumPy: Get the indices of the sorted elements of a given array


Write a NumPy program to get the indices of the sorted elements of a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a NumPy array for student IDs
student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532])

# Displaying the original array
print("Original array:")
print(student_id)

# Sorting the indices of the array's elements in ascending order
i = np.argsort(student_id)

# Displaying the indices of the sorted elements
print("Indices of the sorted elements of a given array:")
print(i) 

Sample Output:

Original array:
[1023 5202 6230 1671 1682 5241 4532]
Indices of the sorted elements of a given array:
[0 3 4 6 1 5 2]

Explanation:

In the above code –

student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532]): This line creates a Numpy array student_id containing seven student IDs.

i = np.argsort(student_id): This line uses the np.argsort function to sort the indices of the student_id array in ascending order. In this case, i will be a Numpy array containing the indices [0, 3, 4, 6, 1, 5, 2]. These indices indicate the sorted order of the student_id array.

Pictorial Presentation:

NumPy: Get the indices of the sorted elements of a given array.

Python-Numpy Code Editor: