Broadcasting
Add Vector to Rows
A 2-row × 3-column grid and a 3-element vector added together by hand. A nested
loop walks each row, then each column, adding the matching vector element to the
cell. The replay shows new_row building column by column before being appended
to result.
By hand
With NumPy
a + v broadcasts v (shape (3,)) across both rows of a (shape (2, 3)),
adding the same vector to every row in one call.
naive.py
grid = [[1, 2, 3], [4, 5, 6]]
vec = [10, 20, 30]
result = []
for row in grid:
new_row = []
for j in range(len(vec)):
new_row.append(row[j] + vec[j])
result.append(new_row)
print('RESULT:', result)
library.py
import numpy as np
grid = [[1, 2, 3], [4, 5, 6]]
vec = [10, 20, 30]
a = np.array(grid)
v = np.array(vec)
result = a + v
print('shape:', a.shape)
print('dtype:', result.dtype)
print('values:', result.tolist())
print('RESULT:', result.tolist())
shape: (2, 3)
dtype: int64
values: [[11, 22, 33], [14, 25, 36]]
RESULT: [[11, 22, 33], [14, 25, 36]]
Implementation notes
- Broadcasting rule: NumPy aligns shapes from the right.
vis(3,),ais(2, 3)— the trailing dimension matches, sovis virtually replicated along the rows axis without copying memory. - The result dtype is
int64because both inputs are integer arrays. If either werefloat64, the result would promote tofloat64. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.