Broadcasting
Normalize Rows
Divide every element in a row by that row's sum so each row sums to 1. This is a common pre-processing step: once every row is a probability vector, rows from different datasets become comparable.
By hand
With NumPy
np.array stores the matrix in a typed buffer. sum(axis=1, keepdims=True)
produces a 2×1 column vector of row sums; dividing the 2×3 array by this 2×1
vector broadcasts automatically — NumPy aligns the singleton dimension and
repeats the division across all three columns without an explicit loop.
naive.py
data = [[3, 3, 6], [4, 2, 2]]
result = []
for row in data:
row_sum = sum(row)
norm_row = [v / row_sum for v in row]
result.append(norm_row)
print('RESULT:', [[round(v, 10) for v in row] for row in result])
library.py
import numpy as np
data = np.array([[3, 3, 6], [4, 2, 2]], dtype=float)
row_sums = data.sum(axis=1, keepdims=True)
result = data / row_sums
print('RESULT:', [[round(v, 10) for v in row] for row in result.tolist()])
RESULT: [[0.25, 0.25, 0.5], [0.5, 0.25, 0.25]]