Data type objects (dtype
)#
A data type object (an instance of numpy.dtype
class)
describes how the bytes in the fixedsize 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 (littleendian or bigendian)
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),
If the data type is a subarray, what is its shape and data type.
To describe the type of scalar data, there are several builtin scalar types in NumPy for various precision of integers, floatingpoint 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 subarray data types in their fields.
Finally, a data type can describe items that are themselves arrays of items of another data type. These subarrays must, however, be of a fixed size.
If an array is created using a datatype describing a subarray, the dimensions of the subarray are appended to the shape of the array when the array is created. Subarrays in a field of a structured type behave differently, see Field access.
Subarrays always have a Ccontiguous memory layout.
Example
A simple data type containing a 32bit bigendian integer: (see Specifying and constructing data types for details on construction)
>>> dt = np.dtype('>i4')
>>> dt.byteorder
'>'
>>> dt.itemsize
4
>>> dt.name
'int32'
>>> dt.type is np.int32
True
The corresponding array scalar type is int32
.
Example
A structured data type containing a 16character string (in field ‘name’) and a subarray of two 64bit floatingpoint number (in field ‘grades’):
>>> dt = np.dtype([('name', np.unicode_, 16), ('grades', np.float64, (2,))])
>>> dt['name']
dtype('<U16')
>>> dt['grades']
dtype(('<f8', (2,)))
Items of an array of this data type are wrapped in an array scalar type that also has two fields:
>>> x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
>>> x[1]
('John', [6., 7.])
>>> x[1]['grades']
array([6., 7.])
>>> type(x[1])
<class 'numpy.void'>
>>> type(x[1]['grades'])
<class 'numpy.ndarray'>
Specifying and constructing data types#
Whenever a datatype 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:

Create a data type object. 
What can be converted to a datatype object is described below:
 Arrayscalar types
The 24 builtin array scalar type objects all convert to an associated datatype object. This is true for their subclasses as well.
Note that not all datatype information can be supplied with a typeobject: for example,
flexible
datatypes have a default itemsize of 0, and require an explicitly given size to be useful.Example
>>> dt = np.dtype(np.int32) # 32bit integer >>> dt = np.dtype(np.complex128) # 128bit complex floatingpoint number
 Generic types
The generic hierarchical type objects convert to corresponding type objects according to the associations:
character
string
Deprecated since version 1.19: This conversion of generic scalar types is deprecated. This is because it can be unexpected in a context such as
arr.astype(dtype=np.floating)
, which casts an array offloat32
to an array offloat64
, even thoughfloat32
is a subdtype ofnp.floating
. Builtin Python types
Several python types are equivalent to a corresponding array scalar when used to generate a
dtype
object:buffer
(all others)
Note that
str
refers to either null terminated bytes or unicode strings depending on the Python version. In code targeting both Python 2 and 3np.unicode_
should be used as a dtype for strings. See Note on string types.Example
>>> dt = np.dtype(float) # Pythoncompatible floatingpoint number >>> dt = np.dtype(int) # Pythoncompatible integer >>> dt = np.dtype(object) # Python object
Note
All other types map to
object_
for convenience. Code should expect that such types may map to a specific (new) dtype in the future. Types with
.dtype
Any type object with a
dtype
attribute: 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 '>'
(bigendian), '<'
(littleendian), or '='
(hardwarenative, the default), to
specify the byte order.
 Onecharacter strings
Each builtin datatype has a character code (the updated Numeric typecodes), that uniquely identifies it.
Example
>>> dt = np.dtype('b') # byte, native byte order >>> dt = np.dtype('>H') # bigendian unsigned short >>> dt = np.dtype('<f') # littleendian singleprecision float >>> dt = np.dtype('d') # doubleprecision floatingpoint number
 Arrayprotocol type strings (see The array interface protocol)
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. The item size must correspond to an existing type, or an error will be raised. The supported kinds are
'?'
boolean
'b'
(signed) byte
'B'
unsigned byte
'i'
(signed) integer
'u'
unsigned integer
'f'
floatingpoint
'c'
complexfloating point
'm'
timedelta
'M'
datetime
'O'
(Python) objects
'S'
,'a'
zeroterminated bytes (not recommended)
'U'
Unicode string
'V'
raw data (
void
)Example
>>> dt = np.dtype('i4') # 32bit signed integer >>> dt = np.dtype('f8') # 64bit floatingpoint number >>> dt = np.dtype('c16') # 128bit complex floatingpoint number >>> dt = np.dtype('a25') # 25length zeroterminated bytes >>> dt = np.dtype('U25') # 25character string
Note on string types
For backward compatibility with Python 2 the
S
anda
typestrings remain zeroterminated bytes andnumpy.string_
continues to aliasnumpy.bytes_
. To use actual strings in Python 3 useU
ornumpy.str_
. For signed bytes that do not need zeroterminationb
ori1
can be used. String with commaseparated fields
A shorthand notation for specifying the format of a structured data type is a commaseparated string of basic formats.
A basic format in this context is an optional shape specifier followed by an arrayprotocol 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 datatype in a field. The generated datatype fields are named
'f0'
,'f1'
, …,'f<N1>'
where N (>1) is the number of commaseparated basic formats in the string. If the optional shape specifier is provided, then the datatype for the corresponding field describes a subarray.Example
field named
f0
containing a 32bit integerfield named
f1
containing a 2 x 3 subarray of 64bit floatingpoint numbersfield named
f2
containing a 32bit floatingpoint number
>>> dt = np.dtype("i4, (2,3)f8, f4")
field named
f0
containing a 3character stringfield named
f1
containing a subarray of shape (3,) containing 64bit unsigned integersfield named
f2
containing a 3 x 4 subarray containing 10character strings
>>> dt = np.dtype("a3, 3u8, (3,4)a10")
 Type strings
Any string in
numpy.sctypeDict
.keys():Example
>>> dt = np.dtype('uint32') # 32bit unsigned integer >>> dt = np.dtype('float64') # 64bit floatingpoint number
(flexible_dtype, itemsize)
The first argument must be an object that is converted to a zerosized flexible datatype object, the second argument is an integer providing the desired itemsize.
Example
>>> dt = np.dtype((np.void, 10)) # 10byte wide data block >>> dt = np.dtype(('U', 10)) # 10character unicode string
(fixed_dtype, shape)
The first argument is any object that can be converted into a fixedsize datatype object. The second argument is the desired shape of this type. If the shape parameter is 1, then the datatype 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 subarray of the given shape.
Example
>>> dt = np.dtype((np.int32, (2,2))) # 2 x 2 integer subarray >>> dt = np.dtype(('i4, (2,3)f8, f4', (2,3))) # 2 x 3 structured subarray
[(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
descr
item in the__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 2tuple of strings where the first string is either a “title” (which may be any string or unicode string) or metadata 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 datatype.
The optional third element field_shape contains the shape if this field represents an array of the datatype in the second element. Note that a 3tuple with a third argument equal to 1 is equivalent to a 2tuple.
This style does not accept align in the
dtype
constructor as it is assumed that all of the memory is accounted for by the array interface description.Example
Datatype with fields
big
(bigendian 32bit integer) andlittle
(littleendian 32bit integer):>>> dt = np.dtype([('big', '>i4'), ('little', '<i4')])
Datatype with fields
R
,G
,B
,A
, each being an unsigned 8bit integer:>>> dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])
{'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 equallength 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
dtype
constructor.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 (None
can be used if no title is desired for that field). The titles can be any object, but when astr
object 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
.Example
Data type with fields
r
,g
,b
,a
, each being an 8bit unsigned integer:>>> dt = np.dtype({'names': ['r','g','b','a'], ... 'formats': [np.uint8, np.uint8, np.uint8, np.uint8]})
Data type with fields
r
andb
(with the given titles), both being 8bit unsigned integers, the first at byte position 0 from the start of the field and the second at position 2:>>> dt = np.dtype({'names': ['r','b'], 'formats': ['u1', 'u1'], ... 'offsets': [0, 2], ... 'titles': ['Red pixel', 'Blue pixel']})
{'field1': ..., 'field2': ..., ...}
This usage is discouraged, because it is ambiguous with the other dictbased 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
attribute of a datatype object.obj should contain string or unicode keys that refer to
(datatype, offset)
or(datatype, offset, title)
tuples.Example
Data type containing field
col1
(10character string at byte position 0),col2
(32bit float at byte position 10), andcol3
(integers at byte position 14):>>> dt = np.dtype({'col1': ('U10', 0), 'col2': (np.float32, 10), ... 'col3': (int, 14)})
(base_dtype, new_dtype)
In NumPy 1.7 and later, this form allows base_dtype to be interpreted as a structured dtype. Arrays created with this dtype will have underlying dtype base_dtype but will have fields and flags taken from new_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 datatype objects with the same total size.
Example
32bit integer, whose first two bytes are interpreted as an integer via field
real
, and the following two bytes via fieldimag
.>>> dt = np.dtype((np.int32,{'real':(np.int16, 0),'imag':(np.int16, 2)}))
32bit integer, which is interpreted as consisting of a subarray of shape
(4,)
containing 8bit integers:>>> dt = np.dtype((np.int32, (np.int8, 4)))
32bit integer, containing fields
r
,g
,b
,a
that interpret the 4 bytes in the integer as four unsigned integers:>>> dt = np.dtype(('i4', [('r','u1'),('g','u1'),('b','u1'),('a','u1')]))
dtype
#
NumPy data type descriptions are instances of the dtype
class.
Attributes#
The type of the data is described by the following dtype
attributes:
A character code (one of 'biufcmMOSUV') identifying the general kind of data. 

A unique character code for each of the 21 different builtin types. 

A unique number for each of the 21 different builtin types. 

The arrayprotocol typestring of this datatype object. 
Size of the data is in turn described by:
A bitwidth name for this datatype. 

The element size of this datatype object. 
Endianness of this data:
A character indicating the byteorder of this datatype object. 
Information about subdatatypes in a structured data type:
Dictionary of named fields defined for this data type, or 

Ordered list of field names, or 
For data types that describe subarrays:
Tuple 

Shape tuple of the subarray if this data type describes a subarray, and 
Attributes providing additional information:
Boolean indicating whether this dtype contains any referencecounted objects in any fields or subdtypes. 

Bitflags describing how this data type is to be interpreted. 

Integer indicating how this dtype relates to the builtin dtypes. 

Boolean indicating whether the byte order of this dtype is native to the platform. 

__array_interface__ description of the datatype. 

The required alignment (bytes) of this datatype according to the compiler. 

Returns dtype for the base element of the subarrays, regardless of their dimension or shape. 
Metadata attached by the user:
Either 
Methods#
Data types have the following method for changing the byte order:

Return a new dtype with a different byte order. 
The following methods implement the pickle protocol:
Helper for pickle. 

Utility method for typing:

Return a parametrized wrapper around the 
Comparison operations:

Return self>=value. 

Return self>value. 

Return self<=value. 

Return self<value. 