Sub topic 11
What apply, iterrows and itertuples really cost
This chapter assumes you can write Python functions and comprehensions, build and index a DataFrame, and read the earlier chapters on column arithmetic and timing with timeit. Here you will learn what each row-wise tool does internally. You will also learn how to pick the cheapest one when vectorising is not possible.
What the three tools have in common
iterrows, itertuples and apply all call Python code once per row. A vectorised expression such as df["price"] * df["qty"] runs one loop in compiled code over the underlying NumPy arrays. A row-wise tool runs the Python interpreter once per row, and that is where the time goes. The tools differ in how much extra work they do to hand you each row.
| Tool | What you receive per row | Extra work per row | Keeps dtypes |
|---|---|---|---|
| `iterrows()` | `(index, Series)` | Builds a new Series | No, values are upcast to a common dtype |
| `itertuples()` | Named tuple | Builds a lightweight tuple | Yes |
| `apply(axis=1)` | A Series passed to your function | Builds a Series, calls your function, collects the results | No, same upcasting as `iterrows` |
| `Series.apply(func)` | One scalar value | One Python call | Yes |
iterrows: a Series per row
iterrows yields each row as a Series. A Series must have a single dtype, so a row of mixed columns is converted to one common dtype. Integers next to floats become floats, and anything next to a string becomes object.
import pandas as pd
df = pd.DataFrame({"id": [1, 2], "price": [10.5, 20.0]})
for idx, row in df.iterrows():
print(idx, row.dtype, row["id"])The output shows float64 and 1.0 for the first row, although id is an integer column. This is a correctness problem as well as a speed problem. Large integer IDs can lose precision when they are converted to float64, and timestamps next to strings become plain objects.
Two more properties follow from the same design:
- Each row is a copy. Assigning to
row["price"]inside the loop does not change the DataFrame. - Creating a Series involves building an index, checking types and allocating memory. That cost is repeated for every row, and it is why
iterrowsis usually the slowest option.
itertuples: the cheaper iterator
itertuples yields one named tuple per row. A tuple does not need a combined dtype, so each field keeps the value and type of its column. It also avoids building an index for every row.
total = 0.0
for row in df.itertuples(index=False):
total += row.price * row.id
print(total)Check these details before relying on it:
- By default the first field is
Index. Passindex=Falseif you do not need it. - Field access is by attribute (
row.price). A column name that is not a valid Python identifier, such as"unit price", or that starts with an underscore, is renamed to a positional name like_0. Your code then silently reads the wrong attribute name. Rename such columns first, or passname=Noneto get plain tuples and unpack them by position. - Tuples are read-only, so you cannot assign through them either.
itertuples is typically several times faster than iterrows. It is still a Python-level loop, so it stays far behind a column expression.
apply(axis=1): a loop with a friendly name
DataFrame.apply(func, axis=1) looks like vectorised code, but internally it loops over rows. It builds a Series for each row, calls func, and then assembles the results. Its cost is about the same as iterrows plus the overhead of collecting results.
def line_total(row):
return row["price"] * row["qty"]
df2 = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
df2["total"] = df2.apply(line_total, axis=1)Other forms of apply have different costs:
Series.apply(func)andSeries.map(func)with a function call it once per element. That is a loop over scalars, with no Series construction. It is cheaper thanaxis=1, but it still runs one Python call per value.DataFrame.apply(func)with the defaultaxis=0callsfunconce per column. Iffuncitself uses vectorised operations, this is cheap because a table has few columns.df.groupby(key).apply(func)callsfunconce per group. With a handful of large groups, this is fine. With hundreds of thousands of small groups, it behaves like a row loop. Built-in aggregations such assumandmean, ortransformwith a built-in name, avoid the per-group Python call.apply(func, axis=1, raw=True)passes each row as a plain NumPy array instead of a Series. This skips the Series construction, so it is faster, but you lose access by column label.
Measuring the four approaches
Time each approach on the same data and check that the results agree first. The check matters because a fast wrong answer is not a speedup.
import timeit
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 20_000
df = pd.DataFrame({
"price": rng.uniform(1, 100, n),
"qty": rng.integers(1, 10, n),
})
def with_iterrows(frame):
values = [row["price"] * row["qty"] for _, row in frame.iterrows()]
return pd.Series(values, index=frame.index)
def with_itertuples(frame):
values = [r.price * r.qty for r in frame.itertuples(index=False)]
return pd.Series(values, 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"]
reference = with_columns(df)
candidates = {
"iterrows": with_iterrows,
"itertuples": with_itertuples,
"apply": with_apply,
"columns": with_columns,
}
for name, func in candidates.items():
assert np.allclose(func(df), reference)
seconds = timeit.timeit(lambda: func(df), number=3) / 3
print(f"{name:<11}{seconds * 1000:10.2f} ms")On typical hardware the order is iterrows and apply slowest, itertuples several times faster, and the column expression faster again by one to three orders of magnitude. Exact numbers depend on your machine, pandas version and row count, so run it yourself. The gap widens as n grows, because the loop versions pay a fixed cost per row.
Choosing between them when you must loop
Use this order when logic cannot be expressed with column operations:
- Try a vectorised form first: masks,
numpy.where,numpy.select,groupbywithtransform,shift,cumsum,mapormerge. - If you must iterate, prefer
itertuplesoveriterrows. It is faster and it preserves dtypes. - If you only need a few columns, loop over them with
zipand skip the row object entirely:
results = []
for price, qty in zip(df["price"], df["qty"]):
results.append(price * qty)This is often as fast as itertuples, or faster, and the code makes it clear which columns the loop reads. To avoid creating a scalar object per element, you can iterate over .to_numpy() instead of the Series.
- Use
apply(axis=1)only when the function really is easier to write on a whole row, the frame is small, and readability matters more than speed. Addraw=Trueif you can work by position. - Write results back as a whole column, either with
df["new"] = resultsor by building a Series withindex=df.index. Never grow a DataFrame row by row inside a loop. Every append copies the data.
Edge cases worth knowing
- Empty frames.
df.apply(func, axis=1)on an empty DataFrame cannot callfuncto learn the output type, so it may return a DataFrame instead of a Series. Test the empty case if your code can receive one. - Return types. When
funcreturns a Series,apply(axis=1)expands the results into a DataFrame with one column per element. That is slow and easy to trigger by accident. Return a scalar when you want one column. - Index labels.
iterrowsyields index labels, not positions. With a non-default index,idxis a label. - Side effects. A function with side effects, such as writing to a file or a database, is a legitimate reason to loop. Batch the work when you can.
Exercise
A colleague replaces df.iterrows() with df.apply(func, axis=1) and reports that the code is now vectorised. Is it? Give two reasons for your answer, and name one change that would actually reduce the cost.
Show answer
No. apply(axis=1) still calls func once per row from Python, and it builds a Series for each row, so its cost is similar to iterrows. It also upcasts mixed-dtype rows to a common dtype, just as iterrows does. To reduce the cost, rewrite func as column expressions (for example df["price"] * df["qty"]). If that is not possible, use itertuples, a zip over the needed columns, or raw=True with position-based access.
Exercise
A DataFrame has columns id (int64), name (object) and score (float64). Inside for _, row in df.iterrows():, what dtype does row have, and why can that be a problem for id? Which iterator avoids the problem?
Show answer
The row Series has dtype object, because the string column forces a single common dtype. Each integer id is then a Python or NumPy object that was converted from the original column. For mixed numeric columns without strings, an int next to a float would become float64 and large IDs could lose precision. itertuples avoids this because each field of the named tuple keeps the value and type of its own column.