NumPy Data Types
Every NumPy array has a single data type, its dtype. It decides how many bytes each element takes and how those bytes are interpreted. Python itself has only a few number types (int, float, complex); NumPy offers many more, sized for memory and speed.
The type characters
Each kind of dtype has a one-letter code, which you will see in dtype strings like '<i8' or '<U5':
| Code | Kind | Common dtypes |
|---|---|---|
b |
boolean | bool |
i |
signed integer | int8, int16, int32, int64 |
u |
unsigned integer | uint8 (0–255, used for image pixels), uint16, … |
f |
floating point | float16, float32, float64 |
c |
complex | complex64, complex128 |
M / m |
datetime / timedelta | datetime64[D], timedelta64[s] |
U |
Unicode string | <U10 (up to 10 characters) |
S |
byte string | S4 |
O |
Python object | anything (slow, avoid) |
V |
void (raw bytes) | used by structured arrays |
Checking the dtype
NumPy picks a dtype from the data you give it:
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1.0, 2.5]).dtype)
print(np.array([True, False]).dtype)
print(np.array(["cat", "horse"]).dtype)
print(np.array([1, 2.5, 3]).dtype) # one float makes everything float
print(np.array([2 + 3j]).dtype)int32
float64
bool
<U5
float64
complex128
Note: The first line says
int32. The default integer type follows the platform: this browser build of Python is a 32-bit WebAssembly program, so whole numbers default toint32. On a normal 64-bit Windows, macOS or Linux computer with NumPy 2 you would seeint64. Passdtype=np.int64when the exact size matters.
<U5 means "little-endian Unicode string, up to 5 characters": the length of the longest item, "horse". If you later assign a longer string, it is cut off to fit.
Choosing the dtype when creating
Pass dtype= to any constructor. You can use a NumPy type object, a Python type or a string code:
import numpy as np
small = np.array([1, 2, 3], dtype=np.int8)
as_float = np.array([1, 2, 3], dtype=float)
four_bytes = np.array([1, 2, 3], dtype="i4")
for arr in (small, as_float, four_bytes):
print(arr, arr.dtype, "bytes per item:", arr.itemsize, "total:", arr.nbytes)[1 2 3] int8 bytes per item: 1 total: 3
[1. 2. 3.] float64 bytes per item: 8 total: 24
[1 2 3] int32 bytes per item: 4 total: 12
Choosing a smaller dtype saves memory: a million int8 values take 1 MB, a million int64 values take 8 MB. The trade-off is range. An int8 holds only −128 to 127.
Converting with astype()
You cannot change an existing array's dtype in place. astype() returns a new array with converted values:
import numpy as np
readings = np.array([1.9, -2.7, 3.5, 0.2])
print(readings.astype(int)) # truncates toward zero
print(readings.astype(bool)) # 0 -> False, anything else -> True
text = np.array(["10", "25", "7"])
numbers = text.astype(np.int64)
print(numbers, numbers.sum())[ 1 -2 3 0]
[ True True True True]
[10 25 7] 42
Notice that astype(int) truncates (−2.7 becomes −2). If you want rounding, call np.round() first, then convert.
When a conversion is impossible, NumPy raises a ValueError:
import numpy as np
try:
np.array(["12", "abc"]).astype(int)
except ValueError as err:
print("ValueError:", err)ValueError: invalid literal for int() with base 10: np.str_('abc')
Overflow: integers wrap around
Fixed-size integers behave differently from Python's unlimited int. When a value doesn't fit, it wraps around silently in array arithmetic:
import numpy as np
pixels = np.array([250, 100, 5], dtype=np.uint8)
print(pixels + 10) # 260 wraps to 4!
print(pixels.astype(np.int16) + 10) # widen first to be safe
print(np.iinfo(np.uint8)) # the limits of a type[ 4 110 15]
[260 110 15]
Machine parameters for uint8
---------------------------------------------------------------
min = 0
max = 255
---------------------------------------------------------------
Tip:
np.iinfo(type)andnp.finfo(type)report the minimum, maximum and precision of integer and float types. Check them whenever you pick a small dtype.
Test yourself
What dtype does np.array([1, 2, 3.0]) get?
- int64
- float64
- object
- mixed
What does np.array([2.9, -2.9]).astype(int) return?
- [3 -3]
- [2 -2]
- [2 -3]
- [3 -2]
What is the result of np.array([255], dtype=np.uint8) + 1?
- [256]
- [0]
- An OverflowError
- [255]