dtype basics
Every array remembers what kind of numbers it holds (whole numbers, decimals and so on) and that choice affects memory and precision.
In this page:
Syntax
arr = np.array([value1, value2], dtype=np.float64)
arr.dtype
arr.astype(np.int32)
dtype basics
The dtype describes the type of every element, such as int64, float64, bool or complex128. NumPy infers it from your data, but you can set it with the dtype argument or convert later with astype. Mixing ints and floats upcasts everything to float.
Note:
Use smaller dtypes such as int8 or float32 to save memory on large arrays.
Example: dtype basics
import numpy as np
a = np.array([1, 2, 3])
b = np.array([1, 2.5, 3])
c = np.array([1, 2, 3], dtype=np.float32)
print(a.dtype, b.dtype, c.dtype)
print("astype int:", b.astype(int))
# Output:
# int64 float64 float32
# astype int: [1 2 3]
Related Topics
Common Mistakes
- Assuming ints stay ints after mixing with floats
- Overflowing small integer types silently
- Forgetting astype returns a new array
Chapter Summary
- dtype sets the element type
- NumPy infers dtype but you can override it
- astype converts to a new dtype
- Mixed int and float becomes float
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: