w3resource

NumPy: Extract all the rows to compute the student weight from a given array (student information) where a specific column starts with a given character

NumPy: Array Object Exercise-205 with Solution

Write a NumPy program to extract all the rows to compute the student weight from a given array (student information) where a specific column starts with a given character.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Setting printing options to display arrays with a maximum line width of 100
np.set_printoptions(linewidth=100)

# Creating a NumPy array containing student data with IDs, class, names, and weights
student = np.array([
    ['01', 'V', 'Debby Pramod', 30.21],
    ['02', 'V', 'Artemiy Ellie', 29.32],
    ['03', 'V', 'Baptist Kamal', 31.00],
    ['04', 'V', 'Lavanya Davide', 30.22],
    ['05', 'V', 'Fulton Antwan', 30.21],
    ['06', 'V', 'Euanthe Sandeep', 31.00],
    ['07', 'V', 'Endzela Sanda', 32.00],
    ['08', 'V', 'Victoire Waman', 29.21],
    ['09', 'V', 'Briar Nur', 30.00],
    ['10', 'V', 'Rose Lykos', 32.00]
])

# Displaying the original array
print("Original array:")
print(student)

# Finding the total weight of students whose names start with a specific character ('E')
char = 'E'
result = student[np.char.startswith(student[:, 2], char)]
print("\nTotal weight, where student name starts with", char)
print(np.round(result[:, 3].astype(float).sum(), 2))

# Finding the total weight of students whose names start with a specific character ('D')
char = 'D'
result = student[np.char.startswith(student[:, 2], char)]
print("\nTotal weight, where student name starts with", char)
print(np.round(result[:, 3].astype(float).sum(), 2)) 

Sample Output:

Original array:
[['01' 'V' 'Debby Pramod' '30.21']
 ['02' 'V' 'Artemiy Ellie' '29.32']
 ['03' 'V' 'Baptist Kamal' '31.0']
 ['04' 'V' 'Lavanya Davide' '30.22']
 ['05' 'V' 'Fulton Antwan' '30.21']
 ['06' 'V' 'Euanthe Sandeep' '31.0']
 ['07' 'V' 'Endzela Sanda' '32.0']
 ['08' 'V' 'Victoire Waman' '29.21']
 ['09' 'V' 'Briar Nur' '30.0']
 ['10' 'V' 'Rose Lykos' '32.0']]

Total weight, where student name starting with E
63.0

Total weight, where student name starting with D
30.21

Python-Numpy Code Editor:

Previous: Write a NumPy program to extract all the rows from a given array where a specific column starts with a given character.
Next: NumPy Random Exercises Home.

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://198.211.115.131/python-exercises/numpy/python-numpy-exercise-205.php