w3resource

NumPy: Sort the student id with increasing height of the students from given students id and height

NumPy Sorting and Searching: Exercise-4 with Solution

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.

Sample Solution:

Python Code:

import numpy as np
student_id = np.array([1023, 5202, 6230, 1671, 1682, 5241, 4532])
student_height = np.array([40., 42., 45., 41., 38., 40., 42.0])
#Sort by studen_id then by student_height
indices = np.lexsort((student_id, student_height))
print("Sorted indices:")
print(indices)
print("Sorted data:")
for n in indices:
  print(student_id[n], student_height[n])

Sample Output:

Sorted indices:
[4 0 5 3 6 1 2]
Sorted data:
1682 38.0
1023 40.0
5241 40.0
1671 41.0
4532 42.0
5202 42.0
6230 45.0

Pictorial Presentation:

NumPy: Sort the student id with increasing height of the students from given students id and height.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal.
Next: Write a NumPy program to get the indices of the sorted elements of a given array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Python: Find the number of occurrence of each values in an iterable

It returns True only if two values point to same object.