NumPy: Get the indices of the sorted elements of a given array
5. Indices of Sorted Elements
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:
For more Practice: Solve these Related Problems:
- Generate the indices that would sort a 1D array using np.argsort and return both the sorted array and the indices.
- Implement a function that, given an unsorted array, returns a new array of indices representing the sorted order.
- Test the index extraction on arrays with duplicate elements to ensure the order is preserved.
- Compare the result of np.argsort with a custom loop-based implementation for learning purposes.
Go to:
PREV : Sort Student IDs by Increasing Height.
NEXT : Sort Complex Array by Real then Imaginary Part.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.