w3resource

NumPy Input and Output: savez_compressed() function

numpy.savez_compressed() function

The savez_compressed() function is used to save several arrays into a single file in compressed .npz format.

If keyword arguments are given, then filenames are taken from the keywords.
If arguments are passed in with no keywords, then stored file names are arr_0, arr_1, etc.

Syntax:

numpy.savez_compressed(file, *args, **kwds)

Version: 1.15.0

Parameter:

Name Description Required /
Optional
file Either the file name (string) or an open file (file-like object) where the data will be saved.
If file is a string or a Path, the .npz extension will be appended to the file name if it is not already there.
str or file
Required
args Arrays to save to the file. Since it is not possible for Python to know the names of the arrays outside savez,
the arrays will be saved with names "arr_0", "arr_1", and so on. These arguments can be any expression.
Arguments
Optional
kwds Arrays to save to the file. Arrays will be saved in the file with the keyword names.
Keyword arguments
Optional

Returns: None

Notes:
The .npz file format is a zipped archive of files named after the variables they contain.
The archive is compressed with zipfile.ZIP_DEFLATED and each file in the archive contains one variable in .npy format.

When opening the saved .npz file with load a NpzFile object is returned.
This is a dictionary-like object which can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.

NumPy.savez_compressed() method Example-1:

>>> import numpy as np
>>> test_array = np.random.rand(2, 4)
>>> test_vector = np.random.rand(3)
>>> np.savez_compressed('/tmp/123', x=test_array, y=test_vector)
>>> loaded = np.load('/tmp/123.npz')
>>> print(np.array_equal(test_array, loaded['x']))

Output:

True

NumPy.savez_compressed() method Example-2:

>>> import numpy as np
>>> test_array = np.random.rand(2, 4)
>>> test_vector = np.random.rand(3)
>>> np.savez_compressed('/tmp/123', x=test_array, y=test_vector)
>>> loaded = np.load('/tmp/123.npz')
>>> print(np.array_equal(test_vector, loaded['y']))

Output:

True

Python - NumPy Code Editor:

Previous: savez() function
Next: loadtxt() function



Share this Tutorial / Exercise on : Facebook and Twitter