Sub topic 4
Why iterrows and Python loops are slow
This chapter assumes you know basic Python (functions, list comprehensions), pandas DataFrames and Series, and NumPy arrays with element-wise operations. By the end you should be able to explain where the time goes in a row-wise loop, tell the common loop patterns apart by cost, and recognize the mistakes that make them worse.
The cost of one row at a time
A pandas column is stored as a contiguous NumPy array of one type. An operation such as df["price"] * df["qty"] hands both arrays to compiled C code. That code walks the memory in a tight loop and never creates a Python object per element.
A Python loop works differently. For every row, the interpreter does these things:
- Fetches the next item from an iterator.
- Builds a Python object for the row, or for each value in it.
- Looks up names and attributes.
- Calls the arithmetic through the generic Python object protocol.
- Stores the result in a list or back into the frame.
Each step costs tens to hundreds of nanoseconds. A compiled loop does the same arithmetic in about a nanosecond per element. On 200,000 rows the gap is the difference between milliseconds and seconds. The gap does not shrink as data grows. It scales linearly with row count, so a job that is tolerable at 10,000 rows becomes a problem at 10 million.
The three common loop patterns
Row-wise code in pandas usually takes one of three forms. They are not equally slow.
iterrows
DataFrame.iterrows() yields (index, Series) pairs. Creating a full Series for every row is expensive. It also has a second problem: a row Series has a single dtype, so a frame with mixed columns gets its values upcast.
import pandas as pd
mixed = pd.DataFrame({"id": [1, 2], "price": [9.5, 3.25]})
for _, row in mixed.iterrows():
print(row.dtype, row["id"])Both rows print float64, and row["id"] prints 1.0 and 2.0 instead of 1 and 2. The integer column was converted to float to fit in one Series. With strings in the frame, the row becomes object dtype, which is slower still and loses type information.
itertuples
DataFrame.itertuples() yields lightweight named tuples. It skips the Series construction and keeps each column's own type. It is typically several times to more than ten times faster than iterrows, but it is still one Python iteration per row.
Index-based access with loc or at
The slowest pattern is the one in the third code example of this tutorial, which assigns into the frame inside the loop:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(5_000),
"qty": rng.integers(1, 10, 5_000),
})
# Slow: one Python-level iteration per row, plus one write per row
for i, row in df.iterrows():
df.loc[i, "total"] = row["price"] * row["qty"]
# Fast: one operation on whole columns
df["total"] = df["price"] * df["qty"]Here two costs add up. iterrows builds a Series per row. Then df.loc[i, "total"] = ... does label lookup, checks whether the column exists, and may reallocate storage. The first assignment also creates the new column, and later writes go through a general-purpose setter that was designed for flexibility, not speed.
Measuring the gap
Do not take the ranking on trust. Time it. This script compares all four approaches on the same data. It uses time.perf_counter, which was covered in the timing chapter.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
n = 20_000
df = pd.DataFrame({
"price": rng.random(n),
"qty": rng.integers(1, 10, n),
})
def timed(label, func):
start = perf_counter()
result = func()
print(f"{label:<22}{perf_counter() - start:8.4f}s")
return result
def with_iterrows():
return [row["price"] * row["qty"] for _, row in df.iterrows()]
def with_itertuples():
return [row.price * row.qty for row in df.itertuples(index=False)]
def with_zip():
return [p * q for p, q in zip(df["price"], df["qty"])]
def vectorized():
return df["price"] * df["qty"]
timed("iterrows", with_iterrows)
timed("itertuples", with_itertuples)
timed("zip over columns", with_zip)
timed("vectorized", vectorized)Exact numbers depend on your machine, but the order is stable. iterrows is slowest, itertuples is much faster, zip over columns is faster again, and the vectorized line is fastest by a wide margin. Run it twice, since the first call can include warm-up costs.
The zip version is worth noticing. It is still a Python loop, yet it beats itertuples because it skips building a named tuple per row. When you truly cannot vectorize, iterating over plain columns (or .to_numpy() / .tolist()) is the least bad loop.
| Pattern | Object created per row | Keeps column dtypes | Relative cost |
|---|---|---|---|
| `iterrows()` | A full Series | No, upcasts to a common dtype | Highest |
| `itertuples()` | A named tuple | Yes | Medium |
| `zip` over columns | A plain tuple | Yes | Lower |
| Vectorized expression | None | Yes | Lowest |
Why the loop is slow: boxing and dispatch
Two internal mechanisms explain most of the cost.
Boxing. A NumPy float64 array holds raw 8-byte numbers. To use one value in a Python loop, the interpreter must wrap it in an object (a numpy.float64 or Python float). That object has a header, a reference count, and a type pointer. Creating and discarding hundreds of thousands of them keeps the allocator and garbage-related bookkeeping busy.
Dispatch. In Python, a * b has to find out at run time what types a and b are and which multiplication to call. A NumPy ufunc (universal function) makes that decision once for the whole array and then runs a specialized loop, often using CPU vector instructions.
Pandas adds its own overhead on top. Indexing a Series by label, constructing a Series, and aligning on an index all involve Python-level checks. These are cheap once and costly 200,000 times.
Edge cases that make loops worse
Several habits turn a slow loop into a very slow one.
- Writing back inside the loop. Each
df.loc[i, col] = valueis a separate indexed write. Build a list and assign it once:df["total"] = totals. The list must have the same length as the frame. - Modifying the frame while iterating. The documentation warns that you should never modify what you are iterating over. Depending on the dtype, the row you receive may be a copy, so changes may not reach the original.
- Chained indexing. An expression like
df[df["qty"] > 5]["total"] = 0writes to a temporary copy and can triggerSettingWithCopyWarning. Use a single.loccall:df.loc[df["qty"] > 5, "total"] = 0. - Growing a frame in a loop. Calling
pd.concatordf.loc[len(df)] = ...on every pass copies data repeatedly. A later chapter covers this. - Duplicate index labels.
df.loc[i, "total"] = ...with a repeated labeliassigns to every matching row, so the loop can give wrong results as well as slow ones.
When a loop is acceptable
Loops are not always wrong. Vectorizing has its own costs in readability and, sometimes, memory.
- Small data. At a few hundred rows, the loop finishes in milliseconds and clarity wins. Check with a timer first.
- Work that depends on the previous row. A running state, such as a balance that resets under some condition, cannot always be written as one array expression. Look first for
cumsum,shift,diff,rolling, orexpanding, which cover many cases. If none fit, a loop over NumPy arrays is the fallback, and a later chapter covers Numba for these hot spots. - Side effects per row. Calling an API or writing a file for each row is dominated by I/O, not by the loop.
- Complex per-row logic with branching on strings or objects. Sometimes a loop over
zipis the clearest correct choice. Check the next chapters onnp.whereandapplyfirst.
The rule from the first chapter still applies: profile, find the step that dominates, and only then rewrite it. A loop that takes 40 ms out of a 40 s pipeline is not your problem.
A rewrite checklist
When you find a slow loop, work through these questions in order.
- Can the body be written as arithmetic, comparison, or string methods on whole columns?
- Is there a branch? Use
np.where,np.select, or boolean masks with.loc. - Does it depend on neighbouring rows? Try
shift,diff,cumsum, orrolling. - Is it a per-group computation? Try
groupbywithtransform,agg, orcumsum. - If nothing fits, iterate over
zipof columns or NumPy arrays, not overiterrows.
After any rewrite, confirm the output is unchanged before you delete the old code. That check has its own chapter.
Exercise
A colleague's loop is for i, row in df.iterrows(): df.loc[i, "total"] = row["price"] * row["qty"]. Name two separate reasons it is slow, and write the one-line replacement.
Show answer
First, iterrows builds a full Series for every row, which costs object creation and forces all values in the row to a common dtype. Second, df.loc[i, "total"] = ... performs a separate indexed write for every row, with label lookup and possible storage changes. The replacement is df["total"] = df["price"] * df["qty"], which multiplies the two columns in compiled code in one call.
Exercise
You run for _, row in df.iterrows(): print(row["id"]) on a frame whose id column is int64 and whose price column is float64. Why do the ids print as 1.0, 2.0, and what loop avoids this?
Show answer
Each row is returned as one Series, which has a single dtype. Pandas upcasts the integer and float values to float64 so they fit together. df.itertuples(index=False) keeps each column's own dtype, so row.id stays an integer. Looping over zip(df["id"], df["price"]) also keeps the types.
Exercise
A balance column must be reset to zero whenever flag is True and otherwise accumulate amount. The three vectorized helpers you tried (cumsum, shift, rolling) do not express it directly. What is the best option, and why is a loop acceptable here?
Show answer
Loop over NumPy arrays (for example df["amount"].to_numpy() and df["flag"].to_numpy()) and write results into a preallocated array, then assign it to the column once. The value at each step depends on the previous result, so there is no single whole-column expression. Looping over arrays avoids the per-row Series and indexed writes that make iterrows slow. If it is still a bottleneck after profiling, compile that function with Numba.