Update field value in NumPy Structured array
3. Update Age Field
Modifying Field Values:
Write a NumPy program that updates the 'age' field for the first individual in the structured array created in exercise 1 to 30.
Sample Solution:
Python Code:
Output:
Original Structured Array: [('Lehi Piero', 25, 5.5) ('Albin Acha', 30, 5.8) ('Zerach Hav', 35, 6.1) ('Edmund Ter', 40, 5.9) ('Laura Feli', 28, 5.7)] Updated Structured Array: [('Lehi Piero', 30, 5.5) ('Albin Acha', 30, 5.8) ('Zerach Hav', 35, 6.1) ('Edmund Ter', 40, 5.9) ('Laura Feli', 28, 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 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'.
- Update 'Age' Field:
- Access the first element of the structured array and update the 'age' field to 30.
- Print Updated Structured Array:
- Print the updated structured array to verify the changes.
For more Practice: Solve these Related Problems:
- Write a Numpy program to update the 'age' field for the first record and then verify the update by printing the entire record.
- Write a Numpy program to increment the 'age' field for the first individual by a computed value based on their height.
- Write a Numpy program to update the 'age' field conditionally for records that meet a specific criterion (e.g., name starts with 'A').
- Write a Numpy program to apply a vectorized operation that sets the 'age' field of the first two records to a fixed value.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.Previous: Access and print 'Name' Field from NumPy Structured array.
Next: Add new record to NumPy Structured array.
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