![]() |
NumPy is a powerful Python framework for numerical computing that supports massive, multi-dimensional arrays and matrices and offers a number of mathematical functions for modifying the arrays. It is an essential store for Python activities involving scientific computing, data analysis, and machine learning. What is a Numpy array?A NumPy array is a multi-dimensional data structure in Python used for numerical computations. It is similar to a list, but it allows for more efficient storage and manipulation of numerical data. Saving Multiple Numpy ArraysSaving multiple NumPy arrays into a single file can be necessary when you want to store related data together or when you need to share or distribute multiple arrays as a single unit. It helps in organizing your data and simplifies the process of loading and accessing the arrays later on. We will discuss some methods to do the same: Creating Sample Arrays
Python3
|
# Save the arrays into a single .npz file np.savez( 'multiple_arrays.npz' , array1 = array1, array2 = array2, array3 = array3) |
# Load the arrays from the .npz file loaded_data = np.load( 'multiple_arrays.npz' ) # Access individual arrays by their names loaded_array1 = loaded_data[ 'array1' ] loaded_array2 = loaded_data[ 'array2' ] loaded_array3 = loaded_data[ 'array3' ] # Now you can use the loaded arrays as needed print (loaded_array1) print (loaded_array2) print (loaded_array3) |
Output:
[1 2 3 4 5]
[10 20 30 40 50]
[0.1 0.2 0.3 0.4 0.5]
We will save the three arrays into a single compressed file named ‘multiple_arrays_compressed.npz’
np.savez_compressed( 'multiple_arrays_compressed.npz' , array1 = array1, array2 = array2, array3 = array3) |
# Load the saved arrays data = np.load( 'multiple_arrays_compressed.npz' ) loaded_array1 = data[ 'array1' ] loaded_array2 = data[ 'array2' ] loaded_array3 = data[ 'array3' ] print (loaded_array1) print (loaded_array2) print (loaded_array3) |
Output:
[1 2 3 4 5]
[10 20 30 40 50]
[0.1 0.2 0.3 0.4 0.5]
Saving multiple arrays using np.savez_compressed()
allows you to store multiple arrays into a single compressed file, reducing disk space usage and improving efficiency during storage and transfer. In contrast, saving a single array using np.save()
generates an uncompressed binary file, which may be less efficient for storing multiple arrays or when storage space is a concern. Additionally, np.savez_compressed()
requires specifying keys for each array, while np.save()
only needs the array and the file name.
Reffered: https://www.geeksforgeeks.org
AI ML DS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |