w3resource

NumPy: From given student name, height, and class sort by class, then height if class are equal

NumPy Sorting and Searching: Exercise-3 with Solution

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.

Sample Solution:

Python Code:

import numpy as np
data_type = [('name', 'S15'), ('class', int), ('height', float)]
students_details = [('James', 5, 48.5), ('Nail', 6, 52.5),('Paul', 5, 42.10), ('Pit', 5, 40.11)]
# create a structured array
students = np.array(students_details, dtype=data_type)   
print("Original array:")
print(students)
print("Sort by class, then height if class are equal:")
print(np.sort(students, order=['class', 'height']))

Sample Output:

Original array:
[(b'James', 5, 48.5 ) (b'Nail', 6, 52.5 ) (b'Paul', 5, 42.1 )
 (b'Pit', 5, 40.11)]
Sort by class, then height if class are equal:
[(b'Pit', 5, 40.11) (b'Paul', 5, 42.1 ) (b'James', 5, 48.5 )
 (b'Nail', 6, 52.5 )]

Pictorial Presentation:

NumPy: From given student name, height, and class sort by class, then height if class are equal.

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 the array on height.
Next: 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.

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.