How to save and load multiple NumPy arrays to and from a single binary file?
8. Multiple Arrays in Single Binary File
Write a NumPy program that saves multiple NumPy arrays to a single binary file using np.savez and then loads them back using np.load.
Sample Solution:
Python Code:
Output:
Original NumPy Arrays: Array 1: [[10 20 30] [40 50 60]] Array 2: [[ 70 80 90] [100 110 120]] Array 3: [130 140 150 160 170 180] Loaded NumPy Arrays from Binary File: Loaded Array 1: [[10 20 30] [40 50 60]] Loaded Array 2: [[ 70 80 90] [100 110 120]] Loaded Array 3: [130 140 150 160 170 180]
Explanation:
- Import NumPy Library: Import the NumPy library to handle arrays.
- Create Multiple NumPy Arrays: Define multiple NumPy arrays with some example data.
- Define Binary File Path: Specify the path where the binary file will be saved.
- Save Multiple Arrays to Binary File: Use np.savez() to save the multiple NumPy arrays to a single binary file, giving each array a name.
- Load Arrays from Binary File: Use np.load() to read the contents of the binary file back into a NumPy object.
- Extract Loaded Arrays: Extract the individual arrays from the loaded data using their respective names.
- Finally print the original NumPy arrays and the loaded arrays to verify that the data was saved and read correctly.
For more Practice: Solve these Related Problems:
- Write a Numpy program to save multiple arrays into a single .npz file using np.savez and then load them back and compare their shapes.
- Write a Numpy program to bundle several arrays into one .npz file and then extract a specific array using its key.
- Write a Numpy program to create a .npz file with multiple arrays, then update one array and resave the file without affecting others.
- Write a Numpy program to save multiple arrays with different data types into a single .npz file and validate type consistency after loading.
Go to:
Previous: How to save and load a NumPy array to and from a Binary file?
Next: How to save and load a NumPy array to and from an HDF5 file?
Python-Numpy Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.