typestar

Broadcasting in Python

Combining arrays of different shapes without loops.

import numpy as np

prices = np.array([10.0, 20.0, 30.0])
taxed = prices * 1.15
shifted = prices + 5

matrix = np.arange(6).reshape(2, 3)
col_bias = np.array([100, 200])
biased = matrix + col_bias[:, np.newaxis]

row = np.array([1, 2, 3])
outer = row[:, np.newaxis] * row[np.newaxis, :]

How it works

  1. A scalar spreads across the whole array.
  2. newaxis reshapes so shapes line up.
  3. An outer product falls out of two 1-D arrays.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
286
Tokens
100
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 Math & shapes, step 3 of 22 in NumPy.

← Previous Next →