w3resource

NumPy: Data types

Data types

NumPy supports following numerical types:

Data type Description Value/Range
bool_ Boolean stored as a byte. True or False
int_ Default integer type. Same as C long; normally either int64 or int32.
intc Identical to C int. Normally int32 or int64.
intp Integer used for indexing. Same as C ssize_t; normally either int32 or int64.
int8 Byte. -128 to 127
int16 Integer. -32768 to 32767
int32 Integer. -2147483648 to 2147483647
int64 Integer. -9223372036854775808 to 9223372036854775807
uint8 Unsigned integer. 0 to 255
uint16 Unsigned integer. 0 to 65535
uint32 Unsigned integer. 0 to 4294967295
uint64 Unsigned integer 0 to 18446744073709551615
float_ Shorthand for float64.  
float16 Half precision float. sign bit, 5 bits exponent, 10 bits mantissa
float32 Single precision float. sign bit, 8 bits exponent, 23 bits mantissa
float64 Double precision float. sign bit, 11 bits exponent, 52 bits mantissa
complex_ Shorthand for complex128.  
complex64 Complex number, two 32-bit floats (real and imaginary components)
complex128 Complex number, two 64-bit floats (real and imaginary components)

There are 5 basic numerical types representing booleans (bool), integers (int), unsigned integers (uint) floating point (float) and complex. Some types, such as int and intp, have differing bitsizes, dependent on the platforms (e.g. 32-bit vs. 64-bit machines).

Here are some examples:

>>> import numpy as np
>>> a = np.float32(2.0)
>>> a
2.0
>>> b = np.int_([3, 5, 7])
>>> b
array([3, 5, 7])

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:

>>> import numpy as np
>>> np.array([3, 5, 7], dtype='f')
array([3., 5., 7.], dtype=float32)

To convert the type of an array, use the .astype() method (preferred) or the type itself as a function. For example:

>> import numpy as np
>>> c = np.arange(5, dtype=np.uint8)
>>> (c.astype(float))
array([ 0.,  1.,  2.,  3.,  4.])
>>> (np.int8(c))
array([0, 1, 2, 3, 4], dtype=int8)

To determine the type of an array, look at the dtype attribute:

>>> import numpy as np
>>> c = np.arange(5, dtype=np.uint8)
>>> print(c.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:

>>> import numpy as np
>>> np.int8(c)
array([0, 1, 2, 3, 4], dtype=int8)
>>> x = np.dtype(int)
>>> x
dtype('int32')
>>> np.issubdtype(x, np.integer)
True
>>> np.issubdtype(x, np.floating)
False

Previous: NumPy Installation
Next: NumPy ndarray



Follow us on Facebook and Twitter for latest update.