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 a pathlib.Path or a file-like object or a string.
  • mmap_mode: The default value of this parameter is None. 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 to True, it will allow reading pickle arrays from .npy and .npz files. The default value of this parameter is False.
  • fix_imports: This parameter is useful when we load pickles generated from the older versions of Python. The default value of this parameter is True.
  • 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 if allow_pickle is set, but the file cannot be loaded in the program.
  • ValueError: It returns this error when a specified file contains an array type object, but allow_pickle is set to False.

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 np
import numpy as np
# creating a numpy array
array = np.array([3,4,51,6,70,8,9,34,56,7,89,87,])
# print array on console
print("array is:", array)
# save array in .npy file as data.npy
np.save('data', array)
print("the array is saved in the file data.npy")
# loading data.npy file data in array2
array2 = np.load('data.npy')
# print loaded data on console
print("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.npy using np.save(). If the .npy extension 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 the data.npy file in the program as array2.
  • Line 14: We print array2 on the console to show the loaded data from the data.npy file.

Free Resources