Every NumPy array has a single data type (dtype) shared by all its elements. Choosing the right dtype affects memory use, speed and accuracy.
Prerequisites
Checking the dtype
import numpy as np
print(np.array([1, 2, 3]).dtype)
print(np.array([1.5, 2.0]).dtype)
print(np.array(['a', 'bc']).dtype)
print(np.array([True, False]).dtype)
Explanation: On Windows with older NumPy versions the default integer may show as int32. <U2 means Unicode strings up to 2 characters.
int64 float64 <U2 bool
Common Data Types
| dtype | Description | Range / Notes |
|---|---|---|
| int8, int16, int32, int64 | Signed integers | int8: -128 to 127 |
| uint8 | Unsigned 8-bit | 0 to 255, used for images |
| float16, float32, float64 | Decimals | float32 is common in deep learning |
| bool | True/False | |
| complex128 | Complex numbers | |
| str_ / U | Text | Fixed length |
| object | Any Python object | Slow, avoid |
Setting the dtype
a = np.array([1, 2, 3], dtype=np.float32)
b = np.zeros(3, dtype='int16')
print(a, a.dtype)
print(b, b.dtype)
[1. 2. 3.] float32 [0 0 0] int16
Converting with astype()
x = np.array([1.7, 2.2, -3.9])
print(x.astype(int))
print(np.array(['10', '20']).astype(float))
Explanation: astype() returns a new array. Converting float to int cuts off the decimal (towards zero); it does not round.
[ 1 2 -3] [10. 20.]
Mixed Types Are Upcast
print(np.array([1, 2.5]).dtype)
print(np.array([1, 'a']))
Explanation: NumPy picks a type that can hold all values, so an int and a float become float, and anything with a string becomes a string.
float64 ['1' 'a']
Overflow
a = np.array([250], dtype=np.uint8)
print(a + 10)
[4]
Memory Usage
a = np.zeros(1000, dtype=np.float64)
b = np.zeros(1000, dtype=np.float32)
print(a.nbytes, b.nbytes, a.itemsize)
8000 4000 8
Common Errors
| Problem | Cause and fix |
|---|---|
ValueError: could not convert string to float |
A string in the array is not a number; clean it before astype(float). |
Practice Exercises
- Create a uint8 array and check what happens at 256.
- Convert an array of strings of numbers to float and find the mean.
Interview Questions
Q: Why use float32 instead of float64 in deep learning?
Half the memory and faster on GPUs, with enough precision for training.
Q: What does astype return?
A new array (copy) with the new dtype.
Summary
Check dtype with .dtype, set it with dtype=, convert with astype(), and watch for overflow in small integer types.
Next: Inspect an Array · Random Arrays
Machine Learning Tutorials, Courses and Certifications