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

By IncludeHelp Last updated : September 14, 2024

Problem statement

Given an array of students ids and array of heights, write a Python program to sort the student id with increasing height of the students from given students id and height.

Solution

To sort the student id with increasing height of the students from given students id and height, use the numpy.lexsort() method by passing the tuple of arrays (student ids array and student height arrays). The numpy.lexsort() method performs an indirect stable sort using a sequence of keys.

Python code to sort the student id with increasing height of the students from given students id and height

# Importing NumPy
import numpy as np

# Arrays to store student IDs and student heights
std_id = np.array([101, 103, 104, 107, 105, 106, 108])
std_height = np.array([50., 62., 55., 31., 48., 60., 72.0])

# Sorting indices based on the given
# 'std_id' and then 'std_height'
sorted_indices = np.lexsort((std_id, std_height))

# Sorted indices
print("Sorted indices:")
print(sorted_indices)

# Displaying the sorted data
print("Sorted data:")
for n in sorted_indices:
    print(std_id[n], std_height[n])

Output

Sorted indices:
[3 4 0 2 5 1 6]
Sorted data:
107 31.0
105 48.0
101 50.0
104 55.0
106 60.0
103 62.0
108 72.0

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.