NumPy | load method
Start your free 7-days trial now!
Numpy's load(~)
method reads a file with extensions .npy
and .npz
and returns either a memory-map, a Numpy array or a dictionary-like of Numpy arrays.
Parameters
1. file
| file-like object
or string
or pathlib.Path
The file to load.
2. mmap_mode
| None
or string
| optional
Whether to return a memory-map or a Numpy array. Memory-maps come in handy when the data you wish to read is so large that it cannot fit in memory. Memory-maps are stored in disk, and data can be accessed via slicing syntax (e.g. [2:5]
).
The allowed values are as follows:
Value | Description |
---|---|
r | Open file just for reading. |
r+ | Open file for both reading and writing. |
w+ | Open file for reading and writing If file does not exist then a new file is created. Writes will override existing content. |
c | Writing is performed on data in memory, and not on the disk. This means that the actual data is read-only. |
None | Load data as a Numpy array. |
By default, mmap_mode=None
.
3. allow_pickle
| boolean
| optional
Whether or not to use pickling to load the array. If your data just consists of numeric data-types, then pickling is not required. By default, allow_pickle=True
.
If the dtype is numeric, then opt for allow_pickle=False
.
As a general rule of thumb, pickles should not be used if they are not required since different versions of Python and Numpy may interprets pickles differently, and so you may not be able to load the files. Moreover, since reading pickled files involve running arbitrary code in the file, the reader will be susceptible to malicious attacks.
4. fix_imports
| boolean
| optional
This is only relevant if you are using Python 3 to read a pickled file that was generated using Python 2. If set to True
, then such a read becomes possible. By default, fix_imports=True
.
5. encoding
| string
| optional
This is only relevant if you are using Python 3 to read a pickled file that was generated using Python 2. The allowed values are "latin1"
, "ASCII"
, and "bytes"
. By default, encoding="ASCII"
.
Return value
The return type depends on whether you're reading a .npy
file or .npz
file as well as the supplied mmap_mode
:
Action | Return type |
---|---|
Reading | Numpy array |
Reading |
|
Reading | Dictionary-like of Numpy arrays |
Examples
Reading .npy files
Let's create a .npy
file to read:
x = np.array([3,4,5])np.save("my_data.npy", x)
This creates a file called "my_data.npy"
in the same directory as the Python script.
To load this file as a Numpy array:
y = np.load("my_data.npy")y
array([3, 4, 5])
To load this file as a memmap
object:
y = np.load("my_data.npy", "r")y
memmap([3, 4, 5])
Reading .npz files
Unlike .npy
files, .npz
contains a bundle of Numpy arrays.
To create a .npz
file:
x = np.array([3,4,5])y = np.array([6,7,8])np.savez("my_data", my_x=x, my_y=y)
To read this .npz
file:
my_arrays = np.load("my_data.npz")print("x", my_arrays["my_x"])print("y", my_arrays["my_y"])
x [3 4 5]y [6 7 8]