w3resource

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

NumPy Sorting and Searching: Exercise-5 with Solution

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:

Previous: Write a NumPy program to sort the student id with increasing height of the students from given students id and height. Print the integer indices that describes the sort order by multiple columns and the sorted data.
Next: Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.