typestar

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

  1. dtype is chosen on creation and can be forced.
  2. astype copies into a new type; overflow is silent.
  3. itemsize and nbytes are the memory cost.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 4 in Types & shapes, step 9 of 22 in NumPy.

← Previous Next →