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


rng = np.random.default_rng()
data = rng.random((7, 3))
dt = data.dtype
dt
[1]:
dtype('float64')

NumPy data types:

Type

Type code

Description

int8, uint8

i1, u1

Signed and unsigned 8-bit (1-byte) integer types

int16, uint16

i2, u2

Signed and unsigned 16-Bit (2 Byte) integer types

int32, uint32

i4, u4

Signed and unsigned 32-Bit (4 Byte) integer types

int64, uint64

i8, u8

Signed and unsigned 64-Bit (8 Byte) integer types

float16

f2

Standard floating point with half precision

float32

f4 or f

Standard floating point with single precision; compatible with C float

float64

f8 or d

Standard floating point with double precision; compatible with C double and Python float object

complex64, complex128, complex256

c8, c16, c32

Complex numbers represented by two 32, 64 or 128 floating point numbers respectively

bool

?

Boolean type that stores the values True and False

object

O

Python object type; a value can be any Python object

string_

S

ASCII string type with fixed length (1 byte per character); to create a string type with length 7, for example, use S7; longer inputs are truncated without warning

unicode_

U

Unicode type with fixed length where the number of bytes is platform-specific; uses the same specification semantics as string_, e.g. U7

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.09647385, 0.18739372, 0.19808419],
       [0.90809816, 0.6350481 , 0.9251651 ],
       [0.11977272, 0.6560006 , 0.8847805 ],
       [0.33568636, 0.6303831 , 0.3406715 ],
       [0.66093606, 0.06444538, 0.9164912 ],
       [0.20784943, 0.8299043 , 0.5469985 ],
       [0.24248955, 0.39786914, 0.8835176 ]], dtype=float32)