Data Types and Casting
Python · NumPy Library
Theory
Every NumPy array has one dtype that describes how each element is stored: int64 for whole numbers (int32 on some 32-bit platforms, including Python running in a browser), float64 for decimals, bool for True/False and '<U5' for short strings. NumPy picks the dtype from the data, and mixing types upcasts to the most general one: np.array([1, 2.5]) becomes float64, and adding a string makes everything a string.
You change the type with astype, which always returns a new array. Casting float to int truncates toward zero, so 99.9 becomes 99 and -2.7 becomes -2; use np.round first if you want rounding. Text numbers such as np.array(['10', '20']).astype(int) become real integers. Smaller types like int8 or float32 save memory, but int8 only holds -128 to 127, so values outside that range wrap around silently.
Why we use it
The dtype decides memory use, speed and what maths is allowed. Knowing it explains surprises like floats appearing after you add one decimal, or text columns that refuse to add up until you cast them.
When to use it
Check .dtype after loading data. Cast text digits to numbers before maths, round before casting floats to int, and use float32 or int32 for very large arrays. Do not use small int types for values that can grow past their range.
How it works
- Array created or loaded
- Check arr.dtype
- Are numbers stored as text? Yes: arr.astype(int) or astype(float). No: Keep the numeric dtype.
- Converting floats to whole numbers? Yes: np.round(arr) first, then astype(int). No: Skip.
- Very large array? Yes: Consider float32 / int32 to save memory. No: Keep 64-bit defaults.
- Correct dtype for the maths ahead
Syntax
arr.dtype
arr.astype(int)
arr.astype('float32')
np.array([1, 2], dtype=np.int8)Example
prices = np.array([99.9, 150.5])
print(prices.astype(int)) # [ 99 150]
print(np.round(prices).astype(int)) # [100 150]Key points
- astype always returns a new array; the original is unchanged
- float to int truncates toward zero (-2.7 becomes -2)
- np.round uses round-half-to-even: 150.5 becomes 150
- One string in the list turns the whole array into text
- int8 holds only -128..127; bigger values wrap around