w3resource

NumPy: From given student name, height, and class sort the array on height

NumPy Sorting and Searching: Exercise-2 with Solution

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.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Defining the data types for the structured array
data_type = [('name', 'S15'), ('class', int), ('height', float)]

# Defining the details of students as a list of tuples
students_details = [('James', 5, 48.5), ('Nail', 6, 52.5), ('Paul', 5, 42.10), ('Pit', 5, 40.11)]

# Creating a structured array 'students' using the defined data type and provided details
students = np.array(students_details, dtype=data_type)

# Displaying the original structured array
print("Original array:")
print(students)

# Sorting the structured array by 'height' field
print("Sort by height")
print(np.sort(students, order='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 height
[(b'Pit', 5, 40.11) (b'Paul', 5, 42.1 ) (b'James', 5, 48.5 )
 (b'Nail', 6, 52.5 )]

Explanation:

In the above code –

data_type = [('name', 'S15'), ('class', int), ('height', float)]: This statement defines a custom data type data_type with three fields: 'name' (a string with a maximum length of 15 characters), 'class' (an integer), and 'height' (a float).

students_details = [('James', 5, 48.5), ('Nail', 6, 52.5),('Paul', 5, 42.10), ('Pit', 5, 40.11)]: This statement creates a list of tuples, where each tuple contains the details of a student (name, class, and height).

students = np.array(students_details, dtype=data_type): This statement creates a structured Numpy array students using the custom data type data_type. It assigns the elements of students_details to the corresponding fields in the array.

print(np.sort(students, order='height')): This statement sorts the students array based on the 'height' field in ascending order and prints the result.

Pictorial Presentation:

NumPy: From given student name, height, and class   sort the array on height.

Python-Numpy Code Editor:

Previous:Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on flattened array.
Next: 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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-sorting-and-searching-exercise-2.php