Sub topic 4
Data types and casting
This chapter assumes you can create arrays and read their shape, as covered earlier. It explains how NumPy chooses a dtype, how to convert between dtypes, and the errors that come from mixing them.
Why every array has one dtype
An ndarray stores homogeneous data. Every element has the same dtype (data type), which fixes how many bytes each element takes and how those bytes are read. That is why NumPy can step through memory quickly, and why a single float in an integer list changes the whole array.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2, 3.5])
c = np.array([1, 2, "x"])
print(a.dtype) # int64 on most 64-bit Linux and macOS systems
print(b.dtype) # float64
print(c.dtype) # <U21, a string typeNumPy picks the smallest common type that holds every value. Mixing numbers and strings gives a string dtype, which is rarely what you want.
Common dtypes
| Dtype | Meaning | Bytes per element |
|---|---|---|
| `int8`, `int16`, `int32`, `int64` | Signed integers | 1, 2, 4, 8 |
| `uint8` | Unsigned integer, 0 to 255 | 1 |
| `float32`, `float64` | Floating point | 4, 8 |
| `bool` | True or False | 1 |
You can request a dtype when you create an array, and read the memory use from itemsize and nbytes.
import numpy as np
x = np.zeros(1000, dtype=np.float32)
print(x.itemsize) # 4
print(x.nbytes) # 4000Casting with astype
astype converts an array to another dtype. It always returns a new array, so it copies the data.
import numpy as np
f = np.array([1.7, 2.9, -1.7])
print(f.astype(np.int64)) # [ 1 2 -1], truncated toward zero
print(np.round(f).astype(np.int64)) # [ 2 3 -2], rounded firstCasting floats to integers truncates toward zero. It does not round. Call np.round first if you want rounding.
Type promotion in arithmetic
When two arrays with different dtypes meet in an operation, NumPy promotes the result to a dtype that can hold both.
import numpy as np
i = np.array([1, 2, 3], dtype=np.int32)
f = np.array([0.5, 0.5, 0.5], dtype=np.float64)
print((i + f).dtype) # float64
print((i / 2).dtype) # float64, true division always gives floatsCommon errors
Integer overflow is silent. Fixed-size integers wrap around when a value does not fit.
import numpy as np
p = np.array([250, 5], dtype=np.uint8)
print(p + np.uint8(10)) # [4 15], 260 wrapped to 4Other frequent mistakes:
- Assigning a float into an integer array truncates it without warning.
a[0] = 2.9on an int array stores2. - Using
float32and expecting exact decimal results. Floats have limited precision, so compare withnp.isclose, not==. - Converting a string array that holds non-numeric text with
astype(float), which raisesValueError.
Exercise
What does np.array([3.9, -3.9]).astype(np.int64) return, and how would you get [4, -4] instead?
Show answer
It returns [3, -3], because astype truncates toward zero. Use np.round(np.array([3.9, -3.9])).astype(np.int64) to round before casting, which gives [4, -4].
Exercise
You run np.array([200], dtype=np.uint8) + np.uint8(100). What is the result, and why?
Show answer
The result is [44]. A uint8 holds 0 to 255, so 300 wraps around to 300 - 256 = 44, with no error raised.