w3resource

How to save and load multiple NumPy arrays to and from a single binary file?

NumPy: I/O Operations Exercise-8 with Solution

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:

import numpy as np

# Create multiple NumPy arrays
array1 = np.array([[10, 20, 30], [40, 50, 60]])
array2 = np.array([[70, 80, 90], [100, 110, 120]])
array3 = np.array([130, 140, 150, 160, 170, 180])

# Define the path to the binary file
binary_file_path = 'multiple_arrays.npz'

# Save multiple NumPy arrays to a single binary file using np.savez
np.savez(binary_file_path, array1=array1, array2=array2, array3=array3)

# Load the NumPy arrays from the binary file using np.load
loaded_data = np.load(binary_file_path)

# Extract the arrays
loaded_array1 = loaded_data['array1']
loaded_array2 = loaded_data['array2']
loaded_array3 = loaded_data['array3']

# Print the original and loaded NumPy arrays
print("Original NumPy Arrays:")
print("Array 1:")
print(array1)
print("Array 2:")
print(array2)
print("Array 3:")
print(array3)

print("\nLoaded NumPy Arrays from Binary File:")
print("Loaded Array 1:")
print(loaded_array1)
print("Loaded Array 2:")
print(loaded_array2)
print("Loaded Array 3:")
print(loaded_array3)

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.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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?

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.