runtime

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

approachuse it when
A · nested loopsTiny data, or no NumPy.
B · broadcastingArithmetic 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

Broadcasting

related comparisons

NumPy slices: views vs copies · DataFrame.apply vs vectorised columns

A · nested loops
B · broadcasting
Compare Python Approaches · Runtime