Follow this tutorial to discover how to save and load an array to and from a pickle file.
NumPy save function()
Before diving into using the load() function, we need to understand the save function.
It is a simple but helpful function that allows you to save an array to a binary file that ends with a .npy extension.
The function definition is as shown below:
The function parameters are discussed below:
- file – this parameter defines the file or filename to which the array is saved. If the provided filename does not have an extension, the function will append it automatically.
- arr – this specifies the array data to be saved to the file.
- allow_pickle – the allow_pickle parameter is a Boolean value that allows or disallows saving the array using Python pickles. It is used primarily for security reasons as pickled loading data can cause arbitrary code execution in maliciously crafted data. By default, the parameter is set to True.
- fix_imports – this parameter forces an array on Python 3 to be pickled in a Python 2 compatible format.
The code below shows how to use the save() function in NumPy.
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
# save array to file
The code above will create a file called myarr.npy, which holds the data of the arr variable.
NumPy load Function
Now that we understand how the save() function works, we can shift our attention to the load() function.
In simple terms, the load function allows you to load the array saved to a .npy file. It acts as the reading version of the save function.
The function syntax is as shown below:
Let us explore the parameters.
The parameters are as follows:
- file – specifies the file to read.
- mmap_mode – allows the file to be memory-mapped using a given mode.
- allow_pickle – allows or disallows loading of picked objects from the .npy file.
- fix_imports – similar to that of the save function. (see above).
- encoding – specifies which encoding to use, especially when reading Python 2 strings.
The function will return the data stored in the specified .npy file.
To illustrate how to use the load() function, let us read the data stored in the myarr.npy file.
The code is as shown below:
arr_loaded = np.load('myarr.npy')
# compare the two arrays
print(arr == arr_loaded)
In the example above, we load the data of the myarr.npy to a new array variable called arr_loaded.
We then compare if the loaded array is equal to the original array. The code above should return an array of Booleans as shown:
[ True True True True True]]
The above indicates that the original array and one loaded from the file are similar.
This article explores how to save and load array objects to and from .npy files using the save and load functions.
Thanks for reading!!