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.

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

approachuse it when
A · apply(axis=1)Row logic that truly can't be expressed with column operations.
B · column arithmeticArithmetic 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

Dates and times in a table

related comparisons

Python loops vs pandas · Loops vs NumPy broadcasting

Uses the NYC Taxi Trips dataset.

A · apply(axis=1)
B · column arithmetic
Compare Python Approaches · Runtime