NumPy | savez_compressed method
Start your free 7-days trial now!
Numpy's savez_compressed(~)
method writes multiple Numpy arrays to a single file in .npz
format. Unlike the savez(~)
method, savez_compressed(~)
compresses the file.
Parameters
1. file
| file
or string
The file to which the Numpy array will be written. The .npz
extension will be appended to the filename if the path does not already include it.
2. args
| Arguments
| optional
The arrays to save, with their names assigned as "arr_0"
, "arr_1"
and so on. These names will be needed later to access the arrays individually.
3. kwd
| Keyword arguments
| optional
The arrays to save, with their names specified by the keyword argument.
Return Value
None.
Examples
Basic usage
To save multiple Numpy arrays:
x = np.array([3,4,5])y = np.array([6,7,8])np.savez_compressed("my_data", x, y)
This saves our arrays in a single file called my_data.npz
, which exists in the same directory as our Python script.
To read this file later, use Numpy's load(~)
method like so:
my_arrays = np.load("my_data.npz")print("x", my_arrays["arr_0"])print("y", my_arrays["arr_1"])
x [3 4 5]y [6 7 8]
Notice how the default name of the arrays are "arr_0"
and "arr_1"
.
You could also iterate over all the arrays like so:
my_arrays = np.load("my_data.npz")for name in my_arrays: print("name:", name, "| array:", my_arrays[name])
name: arr_0 | array: [3 4 5]name: arr_1 | array: [6 7 8]
Naming arrays
Instead of the default names, you can assign custom names to the arrays using keyword arguments:
x = np.array([3,4,5])y = np.array([6,7,8])np.savez_compressed("my_data", my_x=x, my_y=y)
Now, to fetch these arrays later:
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]