NumPy: Extract all the rows from a given array where a specific column starts with a given character
NumPy: Array Object Exercise-204 with Solution
Write a NumPy program to extract all the rows from a given array where a specific column starts with a given character.
Sample array:
[['01' 'V' 'Debby Pramod']
['02' 'V' 'Artemiy Ellie']
['03' 'V' 'Baptist Kamal']
['04' 'V' 'Lavanya Davide']
['05' 'V' 'Fulton Antwan']
['06' 'V' 'Euanthe Sandeep']
['07' 'V' 'Endzela Sanda']
['08' 'V' 'Victoire Waman']
['09' 'V' 'Briar Nur']
['10' 'V' 'Rose Lykos']]
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
student = np.array([
['01', 'V', 'Debby Pramod'],
['02', 'V', 'Artemiy Ellie'],
['03', 'V', 'Baptist Kamal'],
['04', 'V', 'Lavanya Davide'],
['05', 'V', 'Fulton Antwan'],
['06', 'V', 'Euanthe Sandeep'],
['07', 'V', 'Endzela Sanda'],
['08', 'V', 'Victoire Waman'],
['09', 'V', 'Briar Nur'],
['10', 'V', 'Rose Lykos']
])
# Displaying the original array
print("Original array:")
print(student)
# Searching for student names starting with a specific character ('E')
char = 'E'
result = student[np.char.startswith(student[:, 2], char)]
print("\nStudent name starting with", char, ":")
print(result)
# Searching for student IDs starting with a specific character ('1')
char = '1'
result = student[np.char.startswith(student[:, 0], char)]
print("\nStudent id starting with", char, ":")
print(result)
Sample Output:
Original array: [['01' 'V' 'Debby Pramod'] ['02' 'V' 'Artemiy Ellie'] ['03' 'V' 'Baptist Kamal'] ['04' 'V' 'Lavanya Davide'] ['05' 'V' 'Fulton Antwan'] ['06' 'V' 'Euanthe Sandeep'] ['07' 'V' 'Endzela Sanda'] ['08' 'V' 'Victoire Waman'] ['09' 'V' 'Briar Nur'] ['10' 'V' 'Rose Lykos']] Student name starting with E : [['06' 'V' 'Euanthe Sandeep'] ['07' 'V' 'Endzela Sanda']] Student id starting with 1 : [['10' 'V' 'Rose Lykos']]
Python-Numpy Code Editor:
Previous: Write a NumPy program to create a 11x3 array filled with student information (id, class and name) and shuffle the said array rows starting from 3rd to 9th.
Next: 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.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-exercise-204.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics