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:

import numpy as np
np.set_printoptions(linewidth=100)
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]])
print("Original array:")
print(student)
char='E'
result = student[np.char.startswith(student[:,2], char)]
print("\nTotal weight, where student name starting with",char)
print(np.round(result[:, 3].astype(float).sum(), 2))
char='D'
result = student[np.char.startswith(student[:,2], char)]
print("\nTotal weight, where student name starting 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 Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}