module documentation

Binary serialization

NPY format

A simple format for saving numpy arrays to disk with the full information about them.

The .npy format is the standard binary file format in NumPy for persisting a single arbitrary NumPy array on disk. The format stores all of the shape and dtype information necessary to reconstruct the array correctly even on another machine with a different architecture. The format is designed to be as simple as possible while achieving its limited goals.

The .npz format is the standard format for persisting multiple NumPy arrays on disk. A .npz file is a zip file containing multiple .npy files, one for each array.

Capabilities

  • Can represent all NumPy arrays including nested record arrays and object arrays.
  • Represents the data in its native binary form.
  • Supports Fortran-contiguous arrays directly.
  • Stores all of the necessary information to reconstruct the array including shape and dtype on a machine of a different architecture. Both little-endian and big-endian arrays are supported, and a file with little-endian numbers will yield a little-endian array on any machine reading the file. The types are described in terms of their actual sizes. For example, if a machine with a 64-bit C "long int" writes out an array with "long ints", a reading machine with 32-bit C "long ints" will yield an array with 64-bit integers.
  • Is straightforward to reverse engineer. Datasets often live longer than the programs that created them. A competent developer should be able to create a solution in their preferred programming language to read most .npy files that they have been given without much documentation.
  • Allows memory-mapping of the data. See open_memmap.
  • Can be read from a filelike stream object instead of an actual file.
  • Stores object arrays, i.e. arrays containing elements that are arbitrary Python objects. Files with object arrays are not to be mmapable, but can be read and written to disk.

Limitations

  • Arbitrary subclasses of numpy.ndarray are not completely preserved. Subclasses will be accepted for writing, but only the array data will be written out. A regular numpy.ndarray object will be created upon reading the file.

Warning

Due to limitations in the interpretation of structured dtypes, dtypes with fields with empty names will have the names replaced by 'f0', 'f1', etc. Such arrays will not round-trip through the format entirely accurately. The data is intact; only the field names will differ. We are working on a fix for this. This fix will not require a change in the file format. The arrays with such structures can still be saved and restored, and the correct dtype may be restored by using the loadedarray.view(correct_dtype) method.

File extensions

We recommend using the .npy and .npz extensions for files saved in this format. This is by no means a requirement; applications may wish to use these file formats but use an extension specific to the application. In the absence of an obvious alternative, however, we suggest using .npy and .npz.

Version numbering

The version numbering of these formats is independent of NumPy version numbering. If the format is upgraded, the code in numpy.io will still be able to read and write Version 1.0 files.

Format Version 1.0

The first 6 bytes are a magic string: exactly \x93NUMPY.

The next 1 byte is an unsigned byte: the major version number of the file format, e.g. \x01.

The next 1 byte is an unsigned byte: the minor version number of the file format, e.g. \x00. Note: the version of the file format is not tied to the version of the numpy package.

The next 2 bytes form a little-endian unsigned short int: the length of the header data HEADER_LEN.

The next HEADER_LEN bytes form the header data describing the array's format. It is an ASCII string which contains a Python literal expression of a dictionary. It is terminated by a newline (\n) and padded with spaces (\x20) to make the total of len(magic string) + 2 + len(length) + HEADER_LEN be evenly divisible by 64 for alignment purposes.

The dictionary contains three keys:

"descr" : dtype.descr
An object that can be passed as an argument to the numpy.dtype constructor to create the array's dtype.
"fortran_order" : bool
Whether the array data is Fortran-contiguous or not. Since Fortran-contiguous arrays are a common form of non-C-contiguity, we allow them to be written directly to disk for efficiency.
"shape" : tuple of int
The shape of the array.

For repeatability and readability, the dictionary keys are sorted in alphabetic order. This is for convenience only. A writer SHOULD implement this if possible. A reader MUST NOT depend on this.

Following the header comes the array data. If the dtype contains Python objects (i.e. dtype.hasobject is True), then the data is a Python pickle of the array. Otherwise the data is the contiguous (either C- or Fortran-, depending on fortran_order) bytes of the array. Consumers can figure out the number of bytes by multiplying the number of elements given by the shape (noting that shape=() means there is 1 element) by dtype.itemsize.

Format Version 2.0

The version 1.0 format only allowed the array header to have a total size of 65535 bytes. This can be exceeded by structured arrays with a large number of columns. The version 2.0 format extends the header size to 4 GiB. numpy.save will automatically save in 2.0 format if the data requires it, else it will always use the more compatible 1.0 format.

The description of the fourth element of the header therefore has become: "The next 4 bytes form a little-endian unsigned int: the length of the header data HEADER_LEN."

Format Version 3.0

This version replaces the ASCII string (which in practice was latin1) with a utf8-encoded string, so supports structured types with any unicode field names.

Notes

The .npy format, including motivation for creating it and a comparison of alternatives, is described in the :doc:`"npy-format" NEP <neps:nep-0001-npy-format>`, however details have evolved with time and this document is more current.

Function descr_to_dtype Returns a dtype based off the given description.
Function dtype_to_descr Get a serializable descriptor from the dtype.
Function header_data_from_array_1_0 Get the dictionary of header metadata from a numpy.ndarray.
Function magic Return the magic string for the given file format version.
Function open_memmap Open a .npy file as a memory-mapped array.
Function read_array Read an array from an NPY file.
Function read_array_header_1_0 Read an array header from a filelike object using the 1.0 file format version.
Function read_array_header_2_0 Read an array header from a filelike object using the 2.0 file format version.
Function read_magic Read the magic string to get the version of the file format.
Function write_array Write an array to an NPY file, including a header.
Function write_array_header_1_0 Write the header for an array using the 1.0 format.
Function write_array_header_2_0 The 2.0 format allows storing very large structured arrays.
Constant ARRAY_ALIGN Undocumented
Constant BUFFER_SIZE Undocumented
Constant EXPECTED_KEYS Undocumented
Constant GROWTH_AXIS_MAX_DIGITS Undocumented
Constant MAGIC_LEN Undocumented
Constant MAGIC_PREFIX Undocumented
Function _check_version Undocumented
Function _filter_header Clean up 'L' in npz header ints.
Function _has_metadata Undocumented
Function _read_array_header see read_array_header_1_0
Function _read_bytes Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects.
Function _wrap_header Takes a stringified header, and attaches the prefix and padding to it
Function _wrap_header_guess_version Like _wrap_header, but chooses an appropriate version given the contents
Function _write_array_header Write the header for an array and returns the version used
Constant _MAX_HEADER_SIZE Undocumented
Variable _header_size_info Undocumented
def descr_to_dtype(descr): (source)

Returns a dtype based off the given description.

This is essentially the reverse of dtype_to_descr(). It will remove the valueless padding fields created by, i.e. simple fields like dtype('float32'), and then convert the description to its corresponding dtype.

Parameters
descr:objectThe object retrieved by dtype.descr. Can be passed to numpy.dtype() in order to replicate the input dtype.
Returns
dtypedtype - The dtype constructed by the description.
def dtype_to_descr(dtype): (source)

Get a serializable descriptor from the dtype.

The .descr attribute of a dtype object cannot be round-tripped through the dtype() constructor. Simple types, like dtype('float32'), have a descr which looks like a record array with one field with '' as a name. The dtype() constructor interprets this as a request to give a default name. Instead, we construct descriptor that can be passed to dtype().

Parameters
dtype:dtypeThe dtype of the array that will be written to disk.
Returns
objectdescr - An object that can be passed to numpy.dtype() in order to replicate the input dtype.
def header_data_from_array_1_0(array): (source)

Get the dictionary of header metadata from a numpy.ndarray.

Parameters
array:numpy.ndarray
Returns
dictd - This has the appropriate entries for writing its string representation to the header of the file.
def magic(major, minor): (source)

Return the magic string for the given file format version.

Parameters
major:int in[0, 255]
minor:int in[0, 255]
Returns
strmagic
Raises
ValueError if the version cannot be formatted.
def open_memmap(filename, mode='r+', dtype=None, shape=None, fortran_order=False, version=None, *, max_header_size=_MAX_HEADER_SIZE): (source)

Open a .npy file as a memory-mapped array.

This may be used to read an existing file or create a new one.

See Also

numpy.memmap

Parameters
filename:str or path-likeThe name of the file on disk. This may not be a file-like object.
mode:str, optionalThe mode in which to open the file; the default is 'r+'. In addition to the standard file modes, 'c' is also accepted to mean "copy on write." See memmap for the available mode strings.
dtype:data-type, optionalThe data type of the array if we are creating a new file in "write" mode, if not, dtype is ignored. The default value is None, which results in a data-type of float64.
shape:tuple of intThe shape of the array if we are creating a new file in "write" mode, in which case this parameter is required. Otherwise, this parameter is ignored and is thus optional.
fortran_order:bool, optionalWhether the array should be Fortran-contiguous (True) or C-contiguous (False, the default) if we are creating a new file in "write" mode.
version:tuple of int(major, minor) or NoneIf the mode is a "write" mode, then this is the version of the file format used to create the file. None means use the oldest supported version that is able to store the data. Default: None
max_header_size:int, optionalMaximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See ast.literal_eval() for details.
Returns
memmapmarray - The memory-mapped array.
Raises
ValueErrorIf the data or the mode is invalid.
OSErrorIf the file is not found or cannot be opened correctly.
def read_array(fp, allow_pickle=False, pickle_kwargs=None, *, max_header_size=_MAX_HEADER_SIZE): (source)

Read an array from an NPY file.

Parameters
fp:file_like objectIf this is not a real file object, then this may take extra memory and time.
allow_pickle:bool, optional

Whether to allow writing pickled data. Default: False

Changed in version 1.16.3: Made default False in response to CVE-2019-6446.
pickle_kwargs:dictAdditional keyword arguments to pass to pickle.load. These are only useful when loading object arrays saved on Python 2 when using Python 3.
max_header_size:int, optionalMaximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See ast.literal_eval() for details. This option is ignored when allow_pickle is passed. In that case the file is by definition trusted and the limit is unnecessary.
Returns
ndarrayarray - The array from the data on disk.
Raises
ValueErrorIf the data is invalid, or allow_pickle=False and the file contains an object array.
def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE): (source)

Read an array header from a filelike object using the 1.0 file format version.

This will leave the file object located just after the header.

Parameters
fp:filelike objectA file object or something with a .read() method like a file.
max_header_sizeUndocumented
Returns
  • shape: tuple of int - The shape of the array.
  • fortran_order: bool - The array data will be written out directly if it is either C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous before writing it out.
  • dtype: dtype - The dtype of the file's data.
  • max_header_size: int, optional - Maximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See ast.literal_eval() for details.
Raises
ValueErrorIf the data is invalid.
def read_array_header_2_0(fp, max_header_size=_MAX_HEADER_SIZE): (source)

Read an array header from a filelike object using the 2.0 file format version.

This will leave the file object located just after the header.

New in version 1.9.0.
Parameters
fp:filelike objectA file object or something with a .read() method like a file.
max_header_size:int, optionalMaximum allowed size of the header. Large headers may not be safe to load securely and thus require explicitly passing a larger value. See ast.literal_eval() for details.
Returns
  • shape: tuple of int - The shape of the array.
  • fortran_order: bool - The array data will be written out directly if it is either C-contiguous or Fortran-contiguous. Otherwise, it will be made contiguous before writing it out.
  • dtype: dtype - The dtype of the file's data.
Raises
ValueErrorIf the data is invalid.
def read_magic(fp): (source)

Read the magic string to get the version of the file format.

Parameters
fp:filelike object
Returns
def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None): (source)

Write an array to an NPY file, including a header.

If the array is neither C-contiguous nor Fortran-contiguous AND the file_like object is not a real file object, this function will have to copy data in memory.

Parameters
fp:file_like objectAn open, writable file object, or similar object with a .write() method.
array:ndarrayThe array to write to disk.
version:(int, int) or None, optionalThe version number of the format. None means use the oldest supported version that is able to store the data. Default: None
allow_pickle:bool, optionalWhether to allow writing pickled data. Default: True
pickle_kwargs:dict, optionalAdditional keyword arguments to pass to pickle.dump, excluding 'protocol'. These are only useful when pickling objects in object arrays on Python 3 to Python 2 compatible format.
Raises
ValueErrorIf the array cannot be persisted. This includes the case of allow_pickle=False and array being an object array.
Various other errorsIf the array contains Python objects as part of its dtype, the process of pickling them may raise various errors if the objects are not picklable.
def write_array_header_1_0(fp, d): (source)

Write the header for an array using the 1.0 format.

Parameters
fp:filelike object
d:dictThis has the appropriate entries for writing its string representation to the header of the file.
def write_array_header_2_0(fp, d): (source)

Write the header for an array using the 2.0 format.
The 2.0 format allows storing very large structured arrays.
New in version 1.9.0.

Parameters
fp:filelike object
d:dictThis has the appropriate entries for writing its string representation to the header of the file.
ARRAY_ALIGN: int = (source)

Undocumented

Value
64
BUFFER_SIZE = (source)

Undocumented

Value
2**18
EXPECTED_KEYS: set[str] = (source)

Undocumented

Value
set(['descr', 'fortran_order', 'shape'])
GROWTH_AXIS_MAX_DIGITS: int = (source)

Undocumented

Value
21
MAGIC_LEN = (source)

Undocumented

Value
len(MAGIC_PREFIX)+2
MAGIC_PREFIX: bytes = (source)

Undocumented

Value
b'\x93NUMPY'
def _check_version(version): (source)

Undocumented

def _filter_header(s): (source)

Clean up 'L' in npz header ints.

Cleans up the 'L' in strings representing integers. Needed to allow npz headers produced in Python2 to be read in Python3.

Parameters
s:stringNpy file header.
Returns
strheader - Cleaned up header.
def _has_metadata(dt): (source)

Undocumented

def _read_array_header(fp, version, max_header_size=_MAX_HEADER_SIZE): (source)

see read_array_header_1_0

def _read_bytes(fp, size, error_template='ran out of data'): (source)

Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects.

Required as e.g. ZipExtFile in python 2.6 can return less data than requested.

def _wrap_header(header, version): (source)

Takes a stringified header, and attaches the prefix and padding to it

def _wrap_header_guess_version(header): (source)

Like _wrap_header, but chooses an appropriate version given the contents

def _write_array_header(fp, d, version=None): (source)

Write the header for an array and returns the version used

Parameters
fp:filelike object
d:dictThis has the appropriate entries for writing its string representation to the header of the file.
version:tuple or NoneNone means use oldest that works. Providing an explicit version will raise a ValueError if the format does not allow saving this data. Default: None
_MAX_HEADER_SIZE: int = (source)

Undocumented

Value
10000
_header_size_info: dict = (source)

Undocumented