bundles / numpy 2.4.3 / docs
Doc
reference:arrays.dtypes
docs/reference:arrays.dtypes
Data type objects (dtype)
A data type object (an instance of numpy.dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data:
Type of the data (integer, float, Python object, etc.)
Size of the data (how many bytes is in e.g. the integer)
Byte order of the data (
little-endianorbig-endian)If the data type is
structured data type, an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float),what are the names of the "
fields <field>" of the structure, by which they can be accessed,what is the data-type of each
field, andwhich part of the memory block each field takes.
If the data type is a sub-array, what is its shape and data type.
To describe the type of scalar data, there are several built-in scalar types in NumPy for various precision of integers, floating-point numbers, etc. An item extracted from an array, e.g., by indexing, will be a Python object whose type is the scalar type associated with the data type of the array.
Note that the scalar types are not dtype objects, even though they can be used in place of one whenever a data type specification is needed in NumPy.
Structured data types are formed by creating a data type whose field contain other data types. Each field has a name by which it can be accessed. The parent data type should be of sufficient size to contain all its fields; the parent is nearly always based on the void type which allows an arbitrary item size. Structured data types may also contain nested structured sub-array data types in their fields.
Finally, a data type can describe items that are themselves arrays of items of another data type. These sub-arrays must, however, be of a fixed size.
If an array is created using a data-type describing a sub-array, the dimensions of the sub-array are appended to the shape of the array when the array is created. Sub-arrays in a field of a structured type behave differently, see arrays.indexing.fields.
Sub-arrays always have a C-contiguous memory layout.
Specifying and constructing data types
Whenever a data-type is required in a NumPy function or method, either a dtype object or something that can be converted to one can be supplied. Such conversions are done by the dtype constructor:
.. autosummary:: :toctree:generated/ dtype
What can be converted to a data-type object is described below:
dtypeobjectUsed as-is.
None
The default data type:
float64.
Array-scalar types
The 24 built-in array scalar type objects all convert to an associated data-type object. This is true for their sub-classes as well.
Note that not all data-type information can be supplied with a type-object: for example,
flexibledata-types have a default itemsize of 0, and require an explicitly given size to be useful.Generic types
The generic hierarchical type objects convert to corresponding type objects according to the associations:
===================================================== =================== :class:`number`, :class:`inexact`, :class:`floating` :class:`float64` :class:`complexfloating` :class:`complex128` :class:`integer`, :class:`signedinteger` :class:`int\_` :class:`unsignedinteger` :class:`uint` :class:`generic`, :class:`flexible` :class:`void` ===================================================== ===================
Built-in Python types
Several Python types are equivalent to a corresponding array scalar when used to generate a
dtypeobject:=================== =============== Python type NumPy type =================== =============== :class:`int` :class:`int\_` :class:`bool` :class:`bool\_` :class:`float` :class:`float64` :class:`complex` :class:`complex128` :class:`bytes` :class:`bytes\_` :class:`str` :class:`str\_` :class:`memoryview` :class:`void` (all others) :class:`object_` =================== ===============
Note that
str_corresponds to UCS4 encoded unicode strings.Types with
.dtypeAny type object with a
dtypeattribute: The attribute will be accessed and used directly. The attribute must return something that is convertible into a dtype object.
Several kinds of strings can be converted. Recognized strings can be prepended with '>' (big-endian), '<' (little-endian), or '=' (hardware-native, the default), to specify the byte order.
One-character strings
Each built-in data-type has a character code (the updated Numeric typecodes), that uniquely identifies it.
Array-protocol type strings (see arrays.interface)
The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters, and except
b1which represents boolean. The item size must correspond to an existing type, or an error will be raised. The supported kinds are================= ======================== ``'?'``, ``'b1'`` boolean ``'b'`` (signed) byte ``'B'`` unsigned byte ``'i'`` (signed) integer ``'u'`` unsigned integer ``'f'`` floating-point ``'c'`` complex-floating point ``'m'`` timedelta ``'M'`` datetime ``'O'`` (Python) objects ``'S'``, ``'a'`` zero-terminated bytes (not recommended) ``'U'`` Unicode string ``'V'`` raw data (:class:`void`) ================= ========================
String with comma-separated fields
A short-hand notation for specifying the format of a structured data type is a comma-separated string of basic formats.
A basic format in this context is an optional shape specifier followed by an array-protocol type string. Parenthesis are required on the shape if it has more than one dimension. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field. The generated data-type fields are named
'f0','f1', ...,'f<N-1>'where N (>1) is the number of comma-separated basic formats in the string. If the optional shape specifier is provided, then the data-type for the corresponding field describes a sub-array.Type strings
Any string name of a NumPy dtype, e.g.:
(flexible_dtype, itemsize)The first argument must be an object that is converted to a zero-sized flexible data-type object, the second argument is an integer providing the desired itemsize.
(fixed_dtype, shape)The first argument is any object that can be converted into a fixed-size data-type object. The second argument is the desired shape of this type. If the shape parameter is 1, then the data-type object used to be equivalent to fixed dtype. This behaviour is deprecated since NumPy 1.17 and will raise an error in the future. If shape is a tuple, then the new dtype defines a sub-array of the given shape.
[(field_name, field_dtype, field_shape), ...]obj should be a list of fields where each field is described by a tuple of length 2 or 3. (Equivalent to the
descritem in the~object.__array_interface__attribute.)The first element, field_name, is the field name (if this is
''then a standard field name,'f#', is assigned). The field name may also be a 2-tuple of strings where the first string is either a "title" (which may be any string or unicode string) or meta-data for the field which can be any object, and the second string is the "name" which must be a valid Python identifier.The second element, field_dtype, can be anything that can be interpreted as a data-type.
The optional third element field_shape contains the shape if this field represents an array of the data-type in the second element. Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple.
This style does not accept align in the
dtypeconstructor as it is assumed that all of the memory is accounted for by the array interface description.
{'names': ..., 'formats': ..., 'offsets': ..., 'titles': ..., 'itemsize': ...}This style has two required and three optional keys. The names and formats keys are required. Their respective values are equal-length lists with the field names and the field formats. The field names must be strings and the field formats can be any object accepted by
dtypeconstructor.When the optional keys offsets and titles are provided, their values must each be lists of the same length as the names and formats lists. The offsets value is a list of byte offsets (limited to ctypes.c_int) for each field, while the titles value is a list of titles for each field (
Nonecan be used if no title is desired for that field). The titles can be any object, but when astrobject will add another entry to the fields dictionary keyed by the title and referencing the same field tuple which will contain the title as an additional tuple member.The itemsize key allows the total size of the dtype to be set, and must be an integer large enough so all the fields are within the dtype. If the dtype being constructed is aligned, the itemsize must also be divisible by the struct alignment. Total dtype itemsize is limited to ctypes.c_int.
{'field1': ..., 'field2': ..., ...}This usage is discouraged, because it is ambiguous with the other dict-based construction method. If you have a field called 'names' and a field called 'formats' there will be a conflict.
This style allows passing in the
fields <dtype.fields>attribute of a data-type object.obj should contain string or unicode keys that refer to
(data-type, offset)or(data-type, offset, title)tuples.(base_dtype, new_dtype)In NumPy 1.7 and later, this form allows
base_dtypeto be interpreted as a structured dtype. Arrays created with this dtype will have underlying dtypebase_dtypebut will have fields and flags taken fromnew_dtype. This is useful for creating custom structured dtypes, as done in record arrays.This form also makes it possible to specify struct dtypes with overlapping fields, functioning like the 'union' type in C. This usage is discouraged, however, and the union mechanism is preferred.
Both arguments must be convertible to data-type objects with the same total size.
Checking the data type
When checking for a specific data type, use == comparison.
As opposed to Python types, a comparison using is should not be used.
First, NumPy treats data type specifications (everything that can be passed to the dtype constructor) as equivalent to the data type object itself. This equivalence can only be handled through ==, not through is.
Second, there is no guarantee that data type objects are singletons.
dtype
NumPy data type descriptions are instances of the dtype class.
Attributes
The type of the data is described by the following dtype attributes:
.. autosummary:: :toctree:generated/ dtype.type dtype.kind dtype.char dtype.num dtype.str
Size of the data is in turn described by:
.. autosummary:: :toctree:generated/ dtype.name dtype.itemsize
Endianness of this data:
.. autosummary:: :toctree:generated/ dtype.byteorder
Information about sub-data-types in a structured data type:
.. autosummary:: :toctree:generated/ dtype.fields dtype.names
For data types that describe sub-arrays:
.. autosummary:: :toctree:generated/ dtype.subdtype dtype.shape
Attributes providing additional information:
.. autosummary:: :toctree:generated/ dtype.hasobject dtype.flags dtype.isbuiltin dtype.isnative dtype.descr dtype.alignment dtype.base
Metadata attached by the user:
.. autosummary:: :toctree:generated/ dtype.metadata
Methods
Data types have the following method for changing the byte order:
.. autosummary:: :toctree:generated/ dtype.newbyteorder
The following methods implement the pickle protocol:
.. autosummary:: :toctree:generated/ dtype.__reduce__ dtype.__setstate__
Utility method for typing:
.. autosummary:: :toctree:generated/ dtype.__class_getitem__
Comparison operations:
.. autosummary:: :toctree:generated/ dtype.__ge__ dtype.__gt__ dtype.__le__ dtype.__lt__