gotchapythonModeratepending
NumPy broadcasting rules — shape mismatch errors
Viewed 0 times
broadcastingshape mismatchnp.newaxisreshapeoperands could not be broadcast
terminallinuxmacos
Error Messages
Problem
NumPy operations fail with 'operands could not be broadcast together with shapes'. Two arrays that seem compatible can't be combined. The broadcasting rules are confusing.
Solution
Broadcasting rules (right-aligned): (1) Dimensions are compared from the trailing (rightmost) side. (2) Dimensions are compatible if they're equal, or one of them is 1. (3) Missing dimensions on the left are treated as 1. Examples: (3,4) + (4,) works — the (4,) is treated as (1,4). (3,4) + (3,1) works — broadcasts to (3,4). (3,4) + (3,) FAILS — trailing dims 4 and 3 don't match. Fix: reshape with np.newaxis or .reshape(). (3,) -> (3,1): arr[:, np.newaxis]. Common pattern: outer product: a[:, np.newaxis] * b[np.newaxis, :].
Why
Broadcasting avoids creating expanded copies of arrays by virtually repeating values along size-1 dimensions. The right-aligned rule ensures that the most common operations (element-wise on matching shapes) work intuitively.
Revisions (0)
No revisions yet.