Sub topic 11
What apply, iterrows and itertuples really cost
This chapter assumes you can write basic pandas code and have seen column arithmetic, boolean masks and timeit. It compares the three common ways to run Python code once per row, so you can judge when each is acceptable.
Where the cost comes from
All three tools call Python code for every row. That per-row call is the expense. A vectorised column operation runs one compiled loop inside NumPy instead.
iterrows()builds a newSeriesfor every row. Creating that object is slow, and it forces all columns into a single dtype. A row with ints and floats becomes all floats, and a row with strings becomes allobject.itertuples()returns one lightweight named tuple per row. It does not build aSeries, so it is usually much faster thaniterrows(). It also keeps each column's own value type.DataFrame.apply(func, axis=1)calls your function once per row and passes it aSeries, much likeiterrows(). It looks vectorised but is a loop with extra overhead.Series.apply(func)andSeries.map(func)call the function once per value. That avoids building row objects, but it is still one Python call per element.
Comparing them on the same task
This example computes a line total with each approach. It checks that every result matches before timing anything.
import timeit
import numpy as np
import pandas as pd
n = 20_000
df = pd.DataFrame({
"price": np.linspace(1.0, 50.0, n),
"qty": np.arange(n) % 5 + 1,
})
def with_iterrows(frame):
out = []
for _, row in frame.iterrows():
out.append(row["price"] * row["qty"])
return pd.Series(out, index=frame.index)
def with_itertuples(frame):
out = []
for row in frame.itertuples(index=False):
out.append(row.price * row.qty)
return pd.Series(out, index=frame.index)
def with_apply(frame):
return frame.apply(lambda row: row["price"] * row["qty"], axis=1)
def with_columns(frame):
return frame["price"] * frame["qty"]
expected = with_columns(df)
for func in (with_iterrows, with_itertuples, with_apply):
assert np.allclose(func(df), expected)
for func in (with_iterrows, with_apply, with_itertuples, with_columns):
seconds = timeit.timeit(lambda: func(df), number=3) / 3
print(f"{func.__name__:16} {seconds:.4f} s")Exact times depend on your machine and pandas version. The usual ordering is iterrows and apply(axis=1) slowest, itertuples several times faster, and the column expression faster again by a large factor. The gap grows with the number of rows.
Choosing between them
| Situation | Reasonable choice |
|---|---|
| Arithmetic, comparisons, conditions | Column expression, `numpy.where`, `numpy.select` |
| Strings and dates | `.str` and `.dt` accessors |
| Per-value lookup in a dictionary | `Series.map` |
| Logic that depends on several fields and cannot be expressed as columns | `itertuples` |
| Small frame, one-off script | Whatever is clearest |
Prefer itertuples() over iterrows() whenever you must loop. Prefer a plain loop over apply(axis=1) if the function has side effects. Side effects inside apply hide the loop and make the code harder to read.
total = 0.0
for row in df.itertuples(index=False):
total += row.price * row.qtyCommon mistakes
- Treating
apply(axis=1)as vectorised. It is not. Check whether a column expression can do the same job. - Modifying a DataFrame while iterating over it. Build a list of results and assign it as a column afterwards.
- Reading integers out of an
iterrows()row and finding floats. This comes from the single-dtypeSeriesdescribed above. - Column names that are not valid Python identifiers, such as names with spaces.
itertuples()renames these to positional names like_1. Rename the columns first or userow[1]-style indexing.
Exercise
A colleague replaced for _, row in df.iterrows() with df.apply(func, axis=1) and expects a large speedup. Will they get one, and why?
Show answer
Probably not. apply(axis=1) still calls the Python function once per row and builds a Series for each row, so it has about the same cost as iterrows. A real speedup needs a column expression, or itertuples if the logic cannot be vectorised.
Exercise
You must loop over a large DataFrame with columns price and qty, and the logic cannot be vectorised. Which method do you use, and how do you read the price value in each row?
Show answer
Use itertuples(index=False) and read row.price. It avoids creating a Series per row and keeps each value's own type.