Introduction to NumPy and Matplotlib
Chapter 2: NumPy arrays
np.dtype
Another important np.array
attribute that you will need to know is the .dtype
attribute. It is a data type object (a np.dtype
instance) that describes the data type of the elements of the np.array
.
>>> x = np.array([[0, 1], [2, 3]])
>>> print(x.dtype)
int32 # or int64 depending on your machine
>>> print(type(x.dtype))
<class 'numpy.dtype[int64]'>
NumPy will automatically infer the dtype
of an np.array
from the type of elements you passed to the constructor. Unlike a Python list
, elements in a np.array
must be of the same type.
>>> x = np.array([0, 1, 2, 3])
>>> print(x.dtype)
int64 # or int32 depending on your machine
>>> x = np.array([0.0, 1.1, 2, 3])
>>> print(x.dtype)
float64
>>> x = np.array(["a", "b", "c", "d"])
>>> print(x.dtype)
<U1 # a unicode string
int32
refers to a 32-bit integer, while int64
refers to a 64-bit integer. Simply put, you can represent larger numbers with a larger number of bits.
You can also explicitly specify the dtype
in the constructor. This can either be standard Python types (e.g. int
or float
) or a np.dtype
(e.g. np.int32
, np.float64
)
>>> x = np.array([0, 1, 2, 3], dtype=float)
>>> print(x.dtype)
float64
>>> x = np.array([0, 1, 2, 3], dtype=np.int32)
>>> print(x.dtype)
int32
>>> x = np.array([0, 1, 2, 3], dtype=np.uint32)
>>> print(x.dtype)
uint32
>>> x = np.array([0, 1, 2, 3], dtype=np.float64)
>>> print(x.dtype)
float64
uint32
is an unsigned integer (non-negative integer). Useful for when you are not expecting a number to be negative (e.g. counts).