Array dtypes in Python
One dtype for the whole array is what makes numpy fast and strict.
import numpy as np
counts = np.array([1, 2, 3], dtype=np.int32)
ratios = counts.astype(np.float64) / 3
print(counts.dtype, counts.itemsize, counts.nbytes)
print(ratios.dtype, ratios.round(3))
print(np.array([1, 2.5]).dtype)
print(np.array([200, 300]).astype(np.uint8)) # wraps silently
How it works
dtypeis chosen on creation and can be forced.astypecopies into a new type; overflow is silent.itemsizeandnbytesare the memory cost.
Keywords and builtins used here
asprint
The run, in numbers
- Lines
- 9
- Characters to type
- 288
- Tokens
- 99
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 57 seconds.
Step 1 of 4 in Types & shapes, step 9 of 22 in NumPy.