dtype
#
ndarray
is a container for homogeneous data, i.e. all elements must be of the same type. Each array has a dtype
, an object that describes the data type of the array:
[1]:
import numpy as np
data = np.random.randn(7, 3)
dt = data.dtype
dt
[1]:
dtype('float64')
NumPy data types:
Type |
Type code |
Description |
---|---|---|
|
|
Signed and unsigned 8-bit (1-byte) integer types |
|
|
Signed and unsigned 16-Bit (2 Byte) integer types |
|
|
Signed and unsigned 32-Bit (4 Byte) integer types |
|
|
Signed and unsigned 64-Bit (8 Byte) integer types |
|
|
Standard floating point with half precision |
|
|
Standard floating point with single precision; compatible with C |
|
|
Standard floating point with double precision; compatible with C |
|
|
Complex numbers represented by two 32, 64 or 128 floating point numbers respectively |
|
|
Boolean type that stores the values |
|
|
Python object type; a value can be any Python object |
|
|
ASCII string type with fixed length (1 byte per character); to create a string type with length 7, for example, use |
|
|
Unicode type with fixed length where the number of bytes is platform-specific; uses the same specification semantics as
|
Determine the number of elements with itemsize
:
[2]:
dt.itemsize
[2]:
8
Determine the name of the data type:
[3]:
dt.name
[3]:
'float64'
Check data type:
[4]:
dt.type is np.float64
[4]:
True
Change data type with astype
:
[5]:
data_float32 = data.astype(np.float32)
data_float32
[5]:
array([[ 0.12408408, 0.28413823, 1.6867595 ],
[-0.4144261 , -0.5990565 , 0.61371785],
[ 0.16093737, 0.12486719, -0.16383053],
[ 1.0395902 , -1.4354634 , 0.35893318],
[ 0.82148165, -2.134709 , 0.12962751],
[-1.0212289 , 0.72899795, -1.7471288 ],
[-1.8143699 , -1.0880227 , -1.1238078 ]], dtype=float32)