Sub topic 2
Elementwise Operations and Broadcasting
Assume basic Python, vectors, matrices, and NumPy imports. The key working model is that NumPy operations act on array elements, while shape rules decide how arrays align.
Elementwise Operations and Universal Functions
An elementwise operation applies independently to corresponding elements. NumPy’s universal functions, or ufuncs, are optimized functions such as np.sqrt, np.exp, and np.sin.
import numpy as np
x = np.array([1.0, 4.0, 9.0])
y = np.array([10.0, 20.0, 30.0])
print(x + y) # [11. 24. 39.]
print(x * 2) # [2. 8. 18.]
print(np.sqrt(x)) # [1. 2. 3.]The arrays must have compatible shapes. Elementwise multiplication uses *; matrix multiplication uses @.
Reductions and the `axis` Argument
A reduction combines multiple values into fewer values. sum, mean, min, and max are reductions. With a two-dimensional array, axis=0 reduces down the rows, leaving one result per column. axis=1 reduces across the columns, leaving one result per row.
x = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]])
print(x.sum()) # 21.0
print(x.sum(axis=0)) # [5. 7. 9.]
print(x.sum(axis=1)) # [ 6. 15.]Reshaping, Concatenating, and Stacking
reshape changes the shape without changing element order. The total number of elements must stay constant. concatenate joins arrays along an existing axis. stack adds a new axis.
a = np.arange(6).reshape(2, 3)
b = np.full((2, 3), 9)
print(np.concatenate([a, b], axis=0).shape) # (4, 3)
print(np.stack([a, b], axis=0).shape) # (2, 2, 3)Broadcasting Rules
Broadcasting lets NumPy combine compatible shapes without copying values. Compare dimensions from right to left. Two dimensions are compatible when they are equal or one is 1. Missing leading dimensions act like 1.
col = np.arange(3).reshape(3, 1)
row = np.arange(4)
print((col + row).shape) # (3, 4)The column is repeated across columns, and the row is repeated across rows.
Exercise
What is the shape of np.ones((2, 3)) + np.arange(3)?
Show answer
(2, 3), because (3,) matches the final dimension.