compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Loops vs NumPy broadcasting
Turn each station's monthly rainfall into a share of its yearly total.
what differs
rain.sum(axis=1, keepdims=True) has shape (3, 1); dividing a (3, 4) array by it stretches the totals across each row without copying.
at a glance
| approach | use it when |
|---|---|
| A · nested loops | Tiny data, or no NumPy. |
| B · broadcasting | Arithmetic between arrays of compatible shapes: whole-array maths in one expression. |
Watch out: Without keepdims the totals have shape (3,), which NumPy would try to line up with the 4 columns and raise an error.
the outputs
Each approach runs on the same input.
concepts
broadcastingaxiskeepdims
learn it
related comparisons
NumPy slices: views vs copies · DataFrame.apply vs vectorised columns