Sub topic 4
Why iterrows and Python loops are slow
This chapter assumes you know basic Python, pandas DataFrames and Series, and the idea of element-wise operations in NumPy. It explains why row-by-row code is slow, so that the next chapter on vectorization makes sense.
The working model
A pandas column is stored as a contiguous NumPy array of one type. A column of float64 values is a block of memory that compiled C code can scan quickly. When you write df["price"] * df["qty"], pandas hands both arrays to compiled code, which multiplies them in one tight loop.
A Python loop works differently. For each row, the interpreter runs bytecode, creates Python objects, and calls functions. That per-row overhead is tiny, but it is paid once per row. At 200,000 rows it adds up to seconds.
What iterrows does on each step
DataFrame.iterrows() yields an (index, Series) pair for every row. Building that Series is the expensive part:
- pandas collects one value from each column.
- It finds a common dtype for those values. A frame with floats and ints gets upcast to
float64. A frame with strings and numbers becomesobject. - It allocates a new Series with its own index and metadata.
So you pay for a full Series construction per row. The upcasting can also change your data, because integers may come back as floats.
Writing back with df.loc[i, "total"] = ... is worse. Each call does label lookup and may trigger an internal copy or resize.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(20_000),
"qty": rng.integers(1, 10, 20_000),
})
start = perf_counter()
for i, row in df.iterrows():
df.loc[i, "total"] = row["price"] * row["qty"]
print(f"iterrows + loc: {perf_counter() - start:.3f}s")
start = perf_counter()
df["total_vec"] = df["price"] * df["qty"]
print(f"vectorized: {perf_counter() - start:.3f}s")This uses 20,000 rows so the slow version finishes quickly. The vectorized line is usually hundreds of times faster. Exact numbers depend on your machine.
Where the time goes
Faster loops are still loops
Some loop styles are cheaper than iterrows, but none match column operations.
| Pattern | Cost per row | Notes |
|---|---|---|
| `iterrows()` | Highest | Builds a Series, may upcast dtypes |
| `itertuples()` | Lower | Yields lightweight named tuples, keeps dtypes per field |
| `apply(axis=1)` | High | Also builds a Series per row |
| Vectorized column expression | Lowest | Runs in compiled code |
itertuples is a reasonable fallback when the logic truly cannot be expressed on columns, for example calling an external API per row. Even then, it remains a Python loop.
Common errors
- Assuming
apply(axis=1)is vectorized. It calls your function once per row, so it has the same overhead as a loop. - Trusting dtypes from
iterrows. An integer column can arrive as a float because the row Series needed one common dtype. - Optimizing without measuring. A loop over 50 rows is fine. Check the cost with the timing and profiling tools from earlier chapters before rewriting anything.
- Growing a result inside the loop. Appending to a DataFrame per row adds copying on top of the loop overhead. A later chapter covers this.
Recognizing a candidate for rewriting
Look for these signs in a slow pipeline:
- A
forloop overdf.iterrows(),df.index, orrange(len(df)). - Row access such as
df.loc[i, "col"]ordf.iloc[i]inside a loop. - A scalar calculation per row that uses only column values and arithmetic or comparisons.
If the per-row logic uses only the values in that row, it can usually be rewritten as an operation on whole columns. The next chapter shows how.
Exercise
A colleague runs for i, row in df.iterrows(): df.loc[i, "total"] = row["price"] * row["qty"] on 1 million rows and finds it takes minutes. Give two reasons it is slow, and write the faster replacement.
Show answer
Reasons: (1) iterrows builds a new Series for every row, including dtype unification and index creation, and (2) df.loc[i, "total"] = ... does a label lookup and assignment per row, all in the Python interpreter. Replacement: df["total"] = df["price"] * df["qty"], which runs one multiplication over the whole columns in compiled code.
Exercise
Why can an integer column come back as floats when you read it through iterrows?
Show answer
Each row is returned as a single Series, which holds one dtype. If the row mixes ints and floats, pandas upcasts the values to a common type, float64, so the ints become floats. With strings in the row, the Series becomes object dtype.