Every ndarray has one dtype. Casting can overflow. Missing values need a float dtype because integers have no NaN.
Goal
Inspect dtypes, convert with astype, and see integer overflow and result_type.
Default dtypes
print(np.array([12, 7, 2]).dtype)
print(np.array([10.5, 22.0, 31.0]).dtype)
print(np.array([True, False, True]).dtype)astype
units = np.array([[12, 7, 2], [9, 6, 0]], dtype=float)
as_int = units.astype(np.int64)
print(as_int)
print(as_int.dtype)Overflow
big = np.array([200, 100, 50], dtype=np.int8)
print(big)
print(big.astype(np.int16))int8 only holds -128…127. 200 wraps. Safer: start from int64 or float64, then narrow if you must.
Mixing types
units = np.array([12, 7, 2], dtype=np.int64)
prices = np.array([10.5, 22.0, 31.0])
print(np.result_type(units, prices))
print(units * prices)The product is float64 — NumPy promotes rather than truncating prices.
Why NaN is float
vals = np.array([12, 7, 2], dtype=np.int64)
try:
vals[1] = np.nan
except ValueError as err:
print(type(err).__name__, err)
print()
as_float = vals.astype(float)
as_float[1] = np.nan
print(as_float)Pitfall
astype(int) on an array that contains nan fails or becomes an arbitrary integer depending on the path. Convert to float before you store missing values.