NumPy: Save two given arrays into a single file in compressed format and load it
NumPy: Basic Exercise-36 with Solution
Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it.
Sample Solution :
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Importing the 'os' module for operating system-dependent functionality
import os
# Creating a NumPy array 'x' containing integers from 0 to 9 using np.arange()
x = np.arange(10)
# Creating a NumPy array 'y' containing integers from 11 to 19 using np.arange()
y = np.arange(11, 20)
# Printing a message indicating the original arrays 'x' and 'y'
print("Original arrays:")
print(x)
print(y)
# Saving the arrays 'x' and 'y' into a '.npz' file named 'temp_arra.npz' using np.savez()
np.savez('temp_arra.npz', x=x, y=y)
# Printing a message indicating loading arrays from the 'temp_arra.npz' file
print("Load arrays from the 'temp_arra.npz' file:")
# Loading data from 'temp_arra.npz' into variables 'x2' and 'y2' using np.load()
with np.load('temp_arra.npz') as data:
x2 = data['x']
y2 = data['y']
# Printing the loaded arrays 'x2' and 'y2'
print(x2)
print(y2)
Sample Output:
Original arrays: [0 1 2 3 4 5 6 7 8 9] [11 12 13 14 15 16 17 18 19] Load arrays from the 'temp_arra.npz' file: [0 1 2 3 4 5 6 7 8 9] [11 12 13 14 15 16 17 18 19]
Explanation:
In the above exercise -
np.arange(10) creates a 1D array and stores in the variable 'x' with elements ranging from 0 to 9.
y = np.arange(11, 20): creates a 1D array and stores in 'y' with elements ranging from 11 to 19.
np.savez('temp_arra.npz', x=x, y=y): This line saves the NumPy arrays 'x' and 'y' to a compressed binary file named 'temp_arra.npz' using NumPy's native file format. The arrays are given the names 'x' and 'y' in the file.
with np.load('temp_arra.npz') as data:: This line opens the file 'temp_arra.npz' in read mode and loads its contents into a dictionary-like object called 'data'.
x2 = data['x']: This line extracts the 'x' array from the 'data' object and assigns it to the variable 'x2'.
y2 = data['y']: This line extracts the 'y' array from the 'data' object and assigns it to the variable 'y2'.
Finally print(x2) and print(y2) prints the loaded 'x2' array and 'y2' array.
Python-Numpy Code Editor:
Previous: NumPy program to save a given array to a binary file.
Next: NumPy program to save a given array to a text file and load it.
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