dpnp.dtype
- class dpnp.dtype(dtype, align=False, copy=False[, metadata])
Create a data type object.
A numpy array is homogeneous, and contains elements described by a dtype object. A dtype object can be constructed from different combinations of fundamental numeric types.
- Parameters:
dtype -- Object to be converted to a data type object.
align (bool, optional) -- Add padding to the fields to match what a C compiler would output for a similar C-struct. Can be
True
only if obj is a dictionary or a comma-separated string. If a struct dtype is being created, this also sets a sticky alignment flagisalignedstruct
.copy (bool, optional) -- Make a new copy of the data-type object. If
False
, the result may just be a reference to a built-in data-type object.metadata (dict, optional) -- An optional dictionary with dtype metadata.
See also
Examples
Using array-scalar type:
>>> import numpy as np >>> np.dtype(np.int16) dtype('int16')
Structured type, one field name 'f1', containing int16:
>>> np.dtype([('f1', np.int16)]) dtype([('f1', '<i2')])
Structured type, one field named 'f1', in itself containing a structured type with one field:
>>> np.dtype([('f1', [('f1', np.int16)])]) dtype([('f1', [('f1', '<i2')])])
Structured type, two fields: the first field contains an unsigned int, the second an int32:
>>> np.dtype([('f1', np.uint64), ('f2', np.int32)]) dtype([('f1', '<u8'), ('f2', '<i4')])
Using array-protocol type strings:
>>> np.dtype([('a','f8'),('b','S10')]) dtype([('a', '<f8'), ('b', 'S10')])
Using comma-separated field formats. The shape is (2,3):
>>> np.dtype("i4, (2,3)f8") dtype([('f0', '<i4'), ('f1', '<f8', (2, 3))])
Using tuples.
int
is a fixed type, 3 the field's shape.void
is a flexible type, here of size 10:>>> np.dtype([('hello',(np.int64,3)),('world',np.void,10)]) dtype([('hello', '<i8', (3,)), ('world', 'V10')])
Subdivide
int16
into 2int8
's, called x and y. 0 and 1 are the offsets in bytes:>>> np.dtype((np.int16, {'x':(np.int8,0), 'y':(np.int8,1)})) dtype((numpy.int16, [('x', 'i1'), ('y', 'i1')]))
Using dictionaries. Two fields named 'gender' and 'age':
>>> np.dtype({'names':['gender','age'], 'formats':['S1',np.uint8]}) dtype([('gender', 'S1'), ('age', 'u1')])
Offsets in bytes, here 0 and 25:
>>> np.dtype({'surname':('S25',0),'age':(np.uint8,25)}) dtype([('surname', 'S25'), ('age', 'u1')])
Methods
- __getitem__(key, /)
Return self[key].
- __len__()
Return len(self).
- newbyteorder(new_order='S', /)
Return a new dtype with a different byte order.
Changes are also made in all fields and sub-arrays of the data type.
- Parameters:
new_order (string, optional) --
Byte order to force; a value from the byte order specifications below. The default value ('S') results in swapping the current byte order. new_order codes can be any of:
'S' - swap dtype from current to opposite endian
{'<', 'little'} - little endian
{'>', 'big'} - big endian
{'=', 'native'} - native order
{'|', 'I'} - ignore (no change to byte order)
- Returns:
new_dtype -- New dtype object with the given change to the byte order.
- Return type:
Notes
Changes are also made in all fields and sub-arrays of the data type.
Examples
>>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = '<' if sys_is_le else '>' >>> swapped_code = '>' if sys_is_le else '<' >>> import numpy as np >>> native_dt = np.dtype(native_code+'i2') >>> swapped_dt = np.dtype(swapped_code+'i2') >>> native_dt.newbyteorder('S') == swapped_dt True >>> native_dt.newbyteorder() == swapped_dt True >>> native_dt == swapped_dt.newbyteorder('S') True >>> native_dt == swapped_dt.newbyteorder('=') True >>> native_dt == swapped_dt.newbyteorder('N') True >>> native_dt == native_dt.newbyteorder('|') True >>> np.dtype('<i2') == native_dt.newbyteorder('<') True >>> np.dtype('<i2') == native_dt.newbyteorder('L') True >>> np.dtype('>i2') == native_dt.newbyteorder('>') True >>> np.dtype('>i2') == native_dt.newbyteorder('B') True
- __eq__(value, /)
Return self==value.
- __ne__(value, /)
Return self!=value.
- __lt__(value, /)
Return self<value.
- __le__(value, /)
Return self<=value.
- __gt__(value, /)
Return self>value.
- __ge__(value, /)
Return self>=value.
Attributes
- alignment
The required alignment (bytes) of this data-type according to the compiler.
More information is available in the C-API section of the manual.
Examples
>>> import numpy as np >>> x = np.dtype('i4') >>> x.alignment 4
>>> x = np.dtype(float) >>> x.alignment 8
- base
Returns dtype for the base element of the subarrays, regardless of their dimension or shape.
See also
Examples
>>> import numpy as np >>> x = numpy.dtype('8f') >>> x.base dtype('float32')
>>> x = numpy.dtype('i2') >>> x.base dtype('int16')
- byteorder
A character indicating the byte-order of this data-type object.
One of:
'='
native
'<'
little-endian
'>'
big-endian
'|'
not applicable
All built-in data-type objects have byteorder either '=' or '|'.
Examples
>>> import numpy as np >>> dt = np.dtype('i2') >>> dt.byteorder '=' >>> # endian is not relevant for 8 bit numbers >>> np.dtype('i1').byteorder '|' >>> # or ASCII strings >>> np.dtype('S2').byteorder '|' >>> # Even if specific code is given, and it is native >>> # '=' is the byteorder >>> import sys >>> sys_is_le = sys.byteorder == 'little' >>> native_code = '<' if sys_is_le else '>' >>> swapped_code = '>' if sys_is_le else '<' >>> dt = np.dtype(native_code + 'i2') >>> dt.byteorder '=' >>> # Swapped code shows up as itself >>> dt = np.dtype(swapped_code + 'i2') >>> dt.byteorder == swapped_code True
- char
A unique character code for each of the 21 different built-in types.
Examples
>>> import numpy as np >>> x = np.dtype(float) >>> x.char 'd'
- descr
__array_interface__ description of the data-type.
The format is that required by the 'descr' key in the __array_interface__ attribute.
Warning: This attribute exists specifically for __array_interface__, and passing it directly to numpy.dtype will not accurately reconstruct some dtypes (e.g., scalar and subarray dtypes).
Examples
>>> import numpy as np >>> x = np.dtype(float) >>> x.descr [('', '<f8')]
>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.descr [('name', '<U16'), ('grades', '<f8', (2,))]
- fields
Dictionary of named fields defined for this data type, or
None
.The dictionary is indexed by keys that are the names of the fields. Each entry in the dictionary is a tuple fully describing the field:
(dtype, offset[, title])
Offset is limited to C int, which is signed and usually 32 bits. If present, the optional title can be any object (if it is a string or unicode then it will also be a key in the fields dictionary, otherwise it's meta-data). Notice also that the first two elements of the tuple can be passed directly as arguments to the
ndarray.getfield
andndarray.setfield
methods.See also
ndarray.getfield
,ndarray.setfield
Examples
>>> import numpy as np >>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> print(dt.fields) {'grades': (dtype(('float64',(2,))), 16), 'name': (dtype('|S16'), 0)}
- flags
Bit-flags describing how this data type is to be interpreted.
Bit-masks are in
numpy._core.multiarray
as the constants ITEM_HASOBJECT, LIST_PICKLE, ITEM_IS_POINTER, NEEDS_INIT, NEEDS_PYAPI, USE_GETITEM, USE_SETITEM. A full explanation of these flags is in C-API documentation; they are largely useful for user-defined data-types.The following example demonstrates that operations on this particular dtype requires Python C-API.
Examples
>>> import numpy as np >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)]) >>> x.flags 16 >>> np._core.multiarray.NEEDS_PYAPI 16
- hasobject
Boolean indicating whether this dtype contains any reference-counted objects in any fields or sub-dtypes.
Recall that what is actually in the ndarray memory representing the Python object is the memory address of that object (a pointer). Special handling may be required, and this attribute is useful for distinguishing data types that may contain arbitrary Python objects and data-types that won't.
- isalignedstruct
Boolean indicating whether the dtype is a struct which maintains field alignment. This flag is sticky, so when combining multiple structs together, it is preserved and produces new dtypes which are also aligned.
- isbuiltin
Integer indicating how this dtype relates to the built-in dtypes.
Read-only.
0
if this is a structured array type, with fields
1
if this is a dtype compiled into numpy (such as ints, floats etc)
2
if the dtype is for a user-defined numpy type A user-defined type uses the numpy C-API machinery to extend numpy to handle a new array type. See User-defined data-types in the NumPy manual.
Examples
>>> import numpy as np >>> dt = np.dtype('i2') >>> dt.isbuiltin 1 >>> dt = np.dtype('f8') >>> dt.isbuiltin 1 >>> dt = np.dtype([('field1', 'f8')]) >>> dt.isbuiltin 0
- isnative
Boolean indicating whether the byte order of this dtype is native to the platform.
- itemsize
The element size of this data-type object.
For 18 of the 21 types this number is fixed by the data-type. For the flexible data-types, this number can be anything.
Examples
>>> import numpy as np >>> arr = np.array([[1, 2], [3, 4]]) >>> arr.dtype dtype('int64') >>> arr.itemsize 8
>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.itemsize 80
- kind
A character code (one of 'biufcmMOSUV') identifying the general kind of data.
b
boolean
i
signed integer
u
unsigned integer
f
floating-point
c
complex floating-point
m
timedelta
M
datetime
O
object
S
(byte-)string
U
Unicode
V
void
Examples
>>> import numpy as np >>> dt = np.dtype('i4') >>> dt.kind 'i' >>> dt = np.dtype('f8') >>> dt.kind 'f' >>> dt = np.dtype([('field1', 'f8')]) >>> dt.kind 'V'
- metadata
Either
None
or a readonly dictionary of metadata (mappingproxy).The metadata field can be set using any dictionary at data-type creation. NumPy currently has no uniform approach to propagating metadata; although some array operations preserve it, there is no guarantee that others will.
Warning
Although used in certain projects, this feature was long undocumented and is not well supported. Some aspects of metadata propagation are expected to change in the future.
Examples
>>> import numpy as np >>> dt = np.dtype(float, metadata={"key": "value"}) >>> dt.metadata["key"] 'value' >>> arr = np.array([1, 2, 3], dtype=dt) >>> arr.dtype.metadata mappingproxy({'key': 'value'})
Adding arrays with identical datatypes currently preserves the metadata:
>>> (arr + arr).dtype.metadata mappingproxy({'key': 'value'})
But if the arrays have different dtype metadata, the metadata may be dropped:
>>> dt2 = np.dtype(float, metadata={"key2": "value2"}) >>> arr2 = np.array([3, 2, 1], dtype=dt2) >>> (arr + arr2).dtype.metadata is None True # The metadata field is cleared so None is returned
- name
A bit-width name for this data-type.
Un-sized flexible data-type objects do not have this attribute.
Examples
>>> import numpy as np >>> x = np.dtype(float) >>> x.name 'float64' >>> x = np.dtype([('a', np.int32, 8), ('b', np.float64, 6)]) >>> x.name 'void640'
- names
Ordered list of field names, or
None
if there are no fields.The names are ordered according to increasing byte offset. This can be used, for example, to walk through all of the named fields in offset order.
Examples
>>> dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))]) >>> dt.names ('name', 'grades')
- ndim
Number of dimensions of the sub-array if this data type describes a sub-array, and
0
otherwise.Added in version 1.13.0.
Examples
>>> import numpy as np >>> x = np.dtype(float) >>> x.ndim 0
>>> x = np.dtype((float, 8)) >>> x.ndim 1
>>> x = np.dtype(('i4', (3, 4))) >>> x.ndim 2
- num
A unique number for each of the 21 different built-in types.
These are roughly ordered from least-to-most precision.
Examples
>>> import numpy as np >>> dt = np.dtype(str) >>> dt.num 19
>>> dt = np.dtype(float) >>> dt.num 12
- shape
Shape tuple of the sub-array if this data type describes a sub-array, and
()
otherwise.Examples
>>> import numpy as np >>> dt = np.dtype(('i4', 4)) >>> dt.shape (4,)
>>> dt = np.dtype(('i4', (2, 3))) >>> dt.shape (2, 3)
- str
The array-protocol typestring of this data-type object.
- subdtype
Tuple
(item_dtype, shape)
if this dtype describes a sub-array, and None otherwise.The shape is the fixed shape of the sub-array described by this data type, and item_dtype the data type of the array.
If a field whose dtype object has this attribute is retrieved, then the extra dimensions implied by shape are tacked on to the end of the retrieved array.
See also
Examples
>>> import numpy as np >>> x = numpy.dtype('8f') >>> x.subdtype (dtype('float32'), (8,))
>>> x = numpy.dtype('i2') >>> x.subdtype >>>
- type = None