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.
DataFrame.apply vs vectorised columns
Add a tip percentage column to taxi trips.
what differs
apply(axis=1) calls your function once per row with a Series built for that row; column arithmetic does the division over whole arrays in compiled code. Same result, very different speed.
at a glance
| approach | use it when |
|---|---|
| A · apply(axis=1) | Row logic that truly can't be expressed with column operations. |
| B · column arithmetic | Arithmetic and comparisons on columns: almost always. |
Watch out: Python's round() and pandas' .round() both round half to even here, so results match. Use np.where for conditions inside vectorised code.
the outputs
Each approach runs on the same input.
concepts
vectorisationDataFrame.apply
learn it
related comparisons