User guide

NumPy User Guide, Release 1.9.0
>>> import numpy as np
the dtypes are available as np.bool_, np.float32, etc.
Advanced types, not listed in the table above, are explored in section Structured arrays (aka “Record arrays”).
There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point
(float) and complex. Those with numbers in their name indicate the bitsize of the type (i.e. how many bits are needed
to represent a single value in memory). Some types, such as int and intp, have differing bitsizes, dependent on the
platforms (e.g. 32-bit vs. 64-bit machines). This should be taken into account when interfacing with low-level code
(such as C or Fortran) where the raw memory is addressed.
Data-types can be used as functions to convert python numbers to array scalars (see the array scalar section for an
explanation), python sequences of numbers to arrays of that type, or as arguments to the dtype keyword that many
numpy functions or methods accept. Some examples:
>>> import numpy as np
>>> x = np.float32(1.0)
>>> x
1.0
>>> y = np.int_([1,2,4])
>>> y
array([1, 2, 4])
>>> z = np.arange(3, dtype=np.uint8)
>>> z
array([0, 1, 2], dtype=uint8)
Array types can also be referred to by character codes, mostly to retain backward compatibility with older packages
such as Numeric. Some documentation may still refer to these, for example:
>>> np.array([1, 2, 3], dtype=’f’)
array([ 1., 2., 3.], dtype=float32)
We recommend using dtype objects instead.
To convert the type of an array, use the .astype() method (preferred) or the type itself as a function. For example:
>>> z.astype(float)
array([ 0., 1., 2.])
>>> np.int8(z)
array([0, 1, 2], dtype=int8)
Note that, above, we use the Python float object as a dtype. NumPy knows that int refers to np.int_, bool means
np.bool_, that float is np.float_ and complex is np.complex_. The other data-types do not have Python
equivalents.
To determine the type of an array, look at the dtype attribute:
>>> z.dtype
dtype(’uint8’)
dtype objects also contain information about the type, such as its bit-width and its byte-order. The data type can also
be used indirectly to query properties of the type, such as whether it is an integer:
>>> d = np.dtype(int)
>>> d
dtype(’int32’)
>>> np.issubdtype(d, int)
True
10 Chapter 2. Numpy basics