Increase Age field in NumPy Structured array by 1
Field-wise operations:
Write a NumPy program to increase the 'age' field by 1 for all individuals in the structured array created with fields for 'name' (string), 'age' (integer), and 'height' (float).
Sample Solution:
Python Code:
import numpy as np
# Define the data type for the structured array
dtype = [('name', 'U10'), ('age', 'i4'), ('height', 'f4')]
# Create the structured array with sample data
structured_array = np.array([
('Lehi', 25, 5.5),
('Albin', 30, 5.8),
('Zerach', 35, 6.1),
('Edmund', 40, 5.9),
('Laura', 28, 5.7)
], dtype=dtype)
print("Original Structured Array:")
print(structured_array)
# Increase the 'age' field by 1 for all individuals
structured_array['age'] += 1
# Print the updated structured array
print("\nUpdated Structured Array with 'age' field increased by 1:")
print(structured_array)
Output:
Original Structured Array: [('Lehi', 25, 5.5) ('Albin', 30, 5.8) ('Zerach', 35, 6.1) ('Edmund', 40, 5.9) ('Laura', 28, 5.7)] Updated Structured Array with 'age' field increased by 1: [('Lehi', 26, 5.5) ('Albin', 31, 5.8) ('Zerach', 36, 6.1) ('Edmund', 41, 5.9) ('Laura', 29, 5.7)]
Explanation:
- Import libraries:
- Imported numpy as "np" for array creation and manipulation.
- Define Data Type:
- Define the data type for the structured array using a list of tuples. Each tuple specifies a field name and its corresponding data type. The data types are:
- 'U10' for a string of up to 10 characters.
- 'i4' for a 4-byte integer.
- 'f4' for a 4-byte float.
- Create a Structured Array:
- Created the structured array using np.array(), providing sample data for five individuals. Each individual is represented as a tuple with values for 'name', 'age', and 'height'.
- Increase the 'Age' field:
- Increase the 'age' field by 1 for all individuals using structured_array['age'] += 1.
- Print Updated Structured Array:
- Print the updated structured array to verify that the 'age' field has been increased by 1 for all individuals.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics