Sub topic 4
Data types and casting
This chapter assumes you can create arrays and read shape, ndim, and size. It also assumes basic Python numeric types (int, float, bool). After it, you should be able to predict the dtype of a result, convert between dtypes on purpose, and spot the silent errors that fixed-size numbers cause.
Why every array has one dtype
An ndarray stores all its elements in one block of memory. Each element takes the same number of bytes, so NumPy can jump straight to element i without inspecting it. The dtype (data type) is the object that fixes this: it says how many bytes each element uses and how to interpret those bytes.
A Python list does the opposite. Each item is a separate object that carries its own type. That is flexible, but it costs memory and speed. The ndarray trades flexibility for a compact layout and fast loops.
import numpy as np
ints = np.array([1, 2, 3])
floats = np.array([1, 2.5, 3])
small = np.array([1, 2, 3], dtype=np.int8)
print(ints.dtype, floats.dtype, small.dtype) # int64 float64 int8
print(small.itemsize, small.nbytes) # 1 3
print(ints.itemsize, ints.nbytes) # 8 24itemsize is the bytes per element, and nbytes is itemsize * size. The default integer dtype is int64 on most 64-bit Linux and macOS systems. On Windows with NumPy 1.x it is int32. Choose the dtype explicitly when your code must behave the same everywhere.
Common dtypes
| Family | Dtypes | Notes |
|---|---|---|
| Boolean | `bool` | One byte per element. Values are `True` or `False`. |
| Signed integer | `int8`, `int16`, `int32`, `int64` | Number in the name is the bit width. |
| Unsigned integer | `uint8`, `uint16`, `uint32`, `uint64` | No negative values. |
| Floating point | `float16`, `float32`, `float64` | `float64` is the default for Python floats. |
| Complex | `complex64`, `complex128` | Two floats per element. |
| Text and objects | `<U5` (fixed-width string), `object` | Strings and Python objects. Not fast. |
You can name a dtype with the NumPy type (np.float32), a string ("float32" or "f4"), or the Python type (float means float64).
How NumPy picks a dtype
When you build an array from Python values, NumPy picks the smallest common dtype that holds every value:
- All Python ints give the default integer dtype.
- Any float among ints gives
float64. - A string among numbers turns everything into strings.
- An int too large for 64 bits gives
object.
import numpy as np
print(np.array([True, False]).dtype) # bool
print(np.array([1, 2.5]).dtype) # float64
print(np.array([1, "a"]).dtype) # <U21
print(np.array([1, 2**100]).dtype) # objectThe last two results are usually mistakes. A <U21 array holds text, so arithmetic on it fails. An object array stores Python objects and loses the speed advantage. If you see either dtype unexpectedly, check your input data.
Converting with astype
astype returns a new array with the requested dtype. It always copies the data by default, so the original is unchanged.
import numpy as np
a = np.array([1.7, -1.7, 2.5])
b = a.astype(np.int64)
print(b) # [ 1 -1 2]
print(a) # [ 1.7 -1.7 2.5]
print(np.array([0, 1, 2]).astype(bool)) # [False True True]Float to integer conversion truncates toward zero. It does not round, so -1.7 becomes -1, not -2. Use np.round(a).astype(np.int64) if you want rounding.
The casting argument controls how strict the conversion is. With casting="safe", NumPy raises an error if the conversion could lose information.
import numpy as np
a = np.array([1.5, 2.5])
try:
a.astype(np.int64, casting="safe")
except TypeError as e:
print("blocked:", e)
print(np.can_cast(np.int32, np.int64)) # True
print(np.can_cast(np.float64, np.float32)) # FalseThe default for astype is casting="unsafe", which allows anything. Use "safe" in code where a lossy conversion would be a bug.
Limits and overflow
Fixed-width integers have a range. NumPy does not raise an error when array arithmetic leaves that range. The value wraps around.
import numpy as np
a = np.array([250, 251], dtype=np.uint8)
print(a + 10) # [4 5]
print(np.iinfo(np.uint8).max) # 255
print(np.iinfo(np.int8).min) # -128
print(np.finfo(np.float32).eps) # 1.1920929e-07np.iinfo and np.finfo report the limits of an integer or floating-point dtype. Check them when you choose a small dtype to save memory, such as uint8 for image pixels.
Floats do not wrap, but they lose precision. A float32 has about 7 decimal digits of precision, and a float64 has about 15 to 16.
import numpy as np
big = np.float32(16777216) # 2**24
print(big + np.float32(1)) # 16777216.0, the +1 is lost
print(0.1 + 0.2 == 0.3) # False
print(np.isclose(0.1 + 0.2, 0.3)) # TrueNever compare floats with == after arithmetic. Use np.isclose or np.allclose.
Type promotion in operations
When an operation combines two dtypes, NumPy converts both to a common dtype that can represent both. This is type promotion. Use np.result_type to ask what it will pick.
import numpy as np
print(np.result_type(np.int32, np.int64)) # int64
print(np.result_type(np.int32, np.float32)) # float64
print(np.result_type(np.int8, np.uint8)) # int16
print(np.result_type(np.uint64, np.int64)) # float64
x = np.array([1, 2, 3])
print((x / 2).dtype) # float64, / always gives floats
print((x // 2).dtype) # int64
print((np.ones(3, dtype=np.float32) * 2.0).dtype) # float32Some of these results surprise people:
int32plusfloat32givesfloat64, becausefloat32cannot hold everyint32exactly.int8plusuint8givesint16, because neither type contains the other.uint64plusint64has no integer type that holds both, so the result isfloat64.- A Python scalar does not widen an array. Multiplying a
float32array by the Python float2.0staysfloat32. NumPy 2 makes this rule explicit: Python numbers are "weak" and adopt the array's dtype.
The diagram shows a simplified view of safe widening. Arrows point to a type that can hold the values of the source.
The diagram leaves out unsigned types and some exceptions, so use np.result_type when you need an exact answer.
Casting on assignment and in-place operations
Operations that write into an existing array cannot change its dtype. NumPy handles this differently in two cases.
Assigning to an element or slice casts the value silently and may lose data:
import numpy as np
a = np.arange(3) # integer dtype
a[0] = 2.9
print(a) # [2 1 2]In-place operators such as += follow stricter rules. NumPy refuses to put a float result into an integer array:
import numpy as np
a = np.arange(3)
try:
a += 1.5
except TypeError as e:
print("error:", type(e).__name__) # UFuncTypeError
a = a + 1.5 # fine: creates a new float64 array
print(a) # [1.5 2.5 3.5]UFuncTypeError is a subclass of TypeError, so the except clause above catches it. The rule is called same_kind casting: float to float is allowed, but float to int is not. Rebind the name to a new array when you need the dtype to change.
Reductions and dtype
Reductions can use a wider accumulator than the input dtype. sum on small integers accumulates in the platform integer, so it does not overflow where elementwise addition would:
import numpy as np
a = np.array([200, 100], dtype=np.uint8)
print(a.sum()) # 300
print(a.sum().dtype) # uint64
print(a.mean()) # 150.0You can override the accumulator with a.sum(dtype=np.float64). For long float32 arrays this reduces rounding error.
Practical guidelines
- Leave the default
float64unless memory or speed demands otherwise. Halving tofloat32halves memory, but it also costs precision. - Pass
dtype=when you create arrays that must match a file format, a database column, or a GPU library. - Check
a.dtypeafter loading data. A column read asobjector<Uis a sign of dirty input. - Use
casting="safe"in functions where a lossy conversion would be a bug. - Convert to a float dtype before dividing or averaging when you need fractional results from integer data.
Exercise
What are the dtypes of a + b and a * 2.0, given a = np.array([1, 2, 3], dtype=np.int32) and b = np.array([0.5, 0.5, 0.5], dtype=np.float32)? Explain each.
Show answer
a + b is float64. NumPy promotes int32 and float32 to a type that holds both, and float32 has only 24 bits of precision, so float64 is the smallest safe choice. a * 2.0 is float64 as well, because a is an integer array and the Python float forces a float result, and the default float dtype is float64. Check with np.result_type(np.int32, np.float32) and (a * 2.0).dtype.
Exercise
A uint8 array holds [200, 100]. What does a + 100 give, and why does a.sum() give a different kind of answer? Show how to get 300 from elementwise addition.
Show answer
a + 100 gives [44, 200] because 200 + 100 = 300 wraps modulo 256 in uint8, and NumPy raises no error. a.sum() returns 300 because sum accumulates in a wider integer (uint64). To get 300 from elementwise addition, widen first: a.astype(np.int64) + 100 gives [300, 200].