pyodide: loading…

[concept]NumPy Foundations

Broadcasting

# theory

broadcasting

Broadcasting is the rule that lets arrays of different shapes line up. When the shapes match (or one is 1 in a dimension), NumPy stretches the smaller one to fit. No data is copied.

the rule

Two shapes are compatible if, working right-to-left, each pair of dimensions is either equal or one of them is 1.

(3, 4) and (4,) -> compatible, becomes (3, 4) (3, 4) and (3, 1) -> compatible, becomes (3, 4) (3, 4) and (3,) -> NOT compatible, ValueError

broadcasting gone wrong

If your shapes happen to be compatible but you didn't mean them to be, the math runs anyway. Always check shape on both operands before you trust the result.

# examples [3]

# example 01 · scalar broadcasts to every cell

The simplest case: one number applied to a whole array.

1
2
3
4
5
6
🐍
Loading PythonSetting up pandas & numpy...
# example 02 · 1D array broadcasts across a 2D array

Shape (3,) lines up with the last dimension of shape (4, 3). Each row gets the same vector added.

1
2
3
4
5
6
🐍
Loading PythonSetting up pandas & numpy...
# example 03 · when shapes don't line up

The most common bug: forgetting to reshape a vector. NumPy will tell you, but the error wording is dense.

1
2
3
4
5
6
7
8
9
10
11
🐍
Loading PythonSetting up pandas & numpy...

# challenges [2]

# challenge 01/02todo
Given prices = np.array([10, 25, 40, 5]), apply a 15% discount and a $2 shipping surcharge in one expression. Print the result formatted as 'final: [a b c d]' (let numpy print the array).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
🐍
Loading PythonSetting up pandas & numpy...
# challenge 02/02todo
Center every column of m = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) so each column has mean 0. Print the centered matrix on one line and 'col means after: [0. 0. 0.]' on the next.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
🐍
Loading PythonSetting up pandas & numpy...