What is numpy.load() in Python?
Overview
The numpy.load() is used to load arrays or pickled objects from files with .npy, and .npz extensions to volatile memory or program.
Pickling is a process in which Python objects are converted into streams of bytes to store data in file. Therefore, it results in a packed object.
Syntax
numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,encoding='ASCII')
Parameters
It takes the following argument values:
file: This is the file to read. It can be either apathlib.Pathor afile-likeobject or a string.mmap_mode: The default value of this parameter isNone. Other possible values are'+','r','w+', and'c'. It follows the specified memory mapping mode when set to any of these values.
allow_pickle: When set toTrue, it will allow reading pickle arrays from.npyand.npzfiles. The default value of this parameter isFalse.-
fix_imports: This parameter is useful when we load pickles generated from the older versions of Python. The default value of this parameter isTrue. encoding: It is used to select the pickle file reading encoding scheme. The default value of this parameter is'ASCII'.
Return value
It returns the data stored in the files as an array, tuple, dict, and so on.
Exception
It also raises the following exceptions.
OSError: It returns this error when the file is inaccessible or unreadable.UnpicklingError: It returns this error ifallow_pickleis set, but the file cannot be loaded in the program.ValueError: It returns this error when a specified file contains an array type object, butallow_pickleis set toFalse.
Example
In the code snippet below, let's look at how the load() function loads an array or pickle file from memory.
# Program to show numpy.load() working# loading numpy library as alias npimport numpy as np# creating a numpy arrayarray = np.array([3,4,51,6,70,8,9,34,56,7,89,87,])# print array on consoleprint("array is:", array)# save array in .npy file as data.npynp.save('data', array)print("the array is saved in the file data.npy")# loading data.npy file data in array2array2 = np.load('data.npy')# print loaded data on consoleprint("array2 is:", array2)
Explanation
- Line 3: We load the NumPy library into the program.
- Lines 5–7: We create a NumPy static array and print it on the console.
- Line 9: We load the array content as
data.npyusingnp.save(). If the.npyextension is not specified at the end of the filename it will append it by default. - Line 12: We invoke the
np.load()function to load contents from thedata.npyfile in the program asarray2. - Line 14: We print
array2on the console to show the loaded data from thedata.npyfile.