Save NumPy Structured array to a file
NumPy: Structured Arrays Exercise-15 with Solution
Saving Structured Arrays to a File:
Write a NumPy program to save a structured array created with fields for 'name' (string), 'age' (integer), and 'height' (float) to a file using NumPy's save function.
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 Piero', 25, 5.5),
('Albin Achan', 30, 5.8),
('Zerach Hava', 35, 6.1),
('Edmund Tereza', 40, 5.9),
('Laura Felinus', 28, 5.7)
], dtype=dtype)
# Save the structured array to a file
# The file will be saved as 'structured_array.npy'
np.save('structured_array.npy', structured_array)
# Print a message indicating the array has been saved
print("Structured array saved to 'structured_array.npy'")
Output:
Structured array saved to 'structured_array.npy'
Explanation:
- Import Libraries:
- Imported numpy as "np" for array creation, manipulation, and saving to files.
- 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'.
- Save Structured Array:
- Use "np.save()" to save the structured array to a file named 'structured_array.npy'. The array is saved in NumPy's native binary format.
- Print a message indicating that the structured array has been saved to the file 'structured_array.npy'.
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Load data from CSV file into NumPy Structured array.
Next: Iterate over records in NumPy Structured array.
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/save-numpy-structured-array-to-a-file.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics