Sub topic 1
Why Looping Over Rows Is Slow
Looping over a DataFrame row by row is the most common cause of slow pandas code. This chapter explains where the time goes, so the rewrites in later chapters make sense. It also shows how to see the gap on your own machine.
Prerequisites
This chapter assumes you can:
- Write Python functions,
forloops and dictionaries. - Create a pandas DataFrame, select a column, and read a value with
df["col"]. - Recognise a NumPy array and know that it holds values of one type.
You do not need to know how to time code properly. A simple timing demo appears below, and a later chapter covers measurement in detail.
The two styles
Suppose you want a line total for each order, which is price times quantity. There are two ways to write it.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
# Row loop
totals = []
for _, row in df.iterrows():
totals.append(row["price"] * row["qty"])
df["total_loop"] = totals
# Vectorised
df["total"] = df["price"] * df["qty"]Both give the same numbers. The first asks Python to handle one row at a time. The second asks pandas to multiply two whole columns in one step.
Vectorised code expresses an operation on entire columns, so the repeated work happens inside compiled code instead of in a Python loop. The speed difference comes from what happens per row, which the next sections break down.
Where the time goes in a row loop
A row loop pays several costs on every iteration. A column operation pays most of them once.
- Interpreter overhead. Each pass through a Python
forloop runs bytecode: fetch the next item, bind names, call methods, append to a list. A single iteration costs well under a microsecond for trivial work, but a loop body that calls pandas costs far more. - Object creation.
iterrows()builds a newSeriesfor every row. ASeriesis a heavy object with an index, a name, a dtype and internal bookkeeping. Creating one takes many microseconds, which dwarfs the multiplication you wanted. - Boxing. NumPy stores numbers as raw machine values in a packed array. When you read
row["price"], that raw value is wrapped in a Python-level object (a NumPy scalar). Every wrapped value costs an allocation and later a cleanup. - Label lookups.
row["price"]searches the row's index for the label"price". Doing that for every value in every row adds up. - No use of the CPU's strengths. A compiled NumPy loop works through contiguous memory with a tight, typed loop. It can use CPU vector instructions and cache-friendly access. Python-level objects scattered across memory prevent that.
A column expression like df["price"] * df["qty"] does a few Python-level calls in total. It then hands two typed arrays to compiled code that multiplies all the elements in a single loop written in C.
Seeing the gap
This script builds a larger DataFrame, times both styles once, and checks that the results agree.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 100_000
big = pd.DataFrame({
"price": rng.uniform(1, 100, n),
"qty": rng.integers(1, 10, n),
})
start = time.perf_counter()
totals = []
for _, row in big.iterrows():
totals.append(row["price"] * row["qty"])
loop_seconds = time.perf_counter() - start
start = time.perf_counter()
vector = big["price"] * big["qty"]
vector_seconds = time.perf_counter() - start
print(f"loop: {loop_seconds:.3f}s, vectorised: {vector_seconds:.5f}s")
print("same result:", np.allclose(totals, vector))On typical hardware the loop takes seconds and the column expression takes about a millisecond, a difference of several hundred times or more. Your numbers will differ. The ratio is what matters, and it generally grows as the number of rows grows.
The cost scales with rows, not with work
For a small frame, say 100 rows, the difference is invisible. Even a slow loop finishes in milliseconds, which is why loops often survive in code until the data grows.
The loop cost per row is roughly constant and large. The column operation has a small fixed cost for the call, plus a tiny per-element cost inside compiled code. As rows increase, the fixed cost matters less and the per-row gap dominates. A job that takes 2 seconds on a sample can take hours on the full table.
What `iterrows` does to your data
Slowness is not the only problem with iterrows. It also changes your values. Each row is returned as one Series, and a Series has a single dtype. When columns have different dtypes, pandas converts them to a common type.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 15.0], "qty": [3, 1, 4]})
for _, row in df.iterrows():
print(row.dtype, row["qty"], type(row["qty"]).__name__)
breakThis prints float64 3.0 float64. The integer column qty was converted to a float. If one of your columns held strings, the whole row would become object dtype, and every number in it would become a Python-level object. Large integers can lose precision when converted to floats, and integer IDs can appear as 3.0. Column operations avoid this because each column keeps its own dtype.
Why column storage makes rows expensive
A DataFrame stores its data by column. Columns of the same dtype are grouped into blocks of contiguous memory. Reading a whole column is a quick view into one such block. Reading one row means collecting one value from each column's block and assembling them into a new object. The data layout favours column operations, and row access works against it.
This is also why chained scalar access inside a loop is poor practice. Patterns like df.loc[i, "price"] or df["price"][i] repeat a label lookup and build intermediate objects for each single value.
Other loop shapes that cost the same
The same costs appear in code that does not use iterrows:
| Pattern | Main extra cost per row |
|---|---|
| `for i in range(len(df))` with `df.loc[i, "col"]` | Label lookup and scalar extraction for every value read |
| `for i in df.index` with `df.at[i, "col"] = x` | One write call per cell, with index lookup each time |
| `df.apply(func, axis=1)` | A new `Series` per row, plus a Python function call |
| `for x in df["col"]` | Boxing each element, but no `Series` per row |
| `df.itertuples()` | One lightweight tuple per row, with no `Series` |
The last two are cheaper than iterrows, yet they are still Python-level loops. A later chapter compares apply, iterrows and itertuples in detail. The point here is that moving from one loop style to another reduces the cost without removing it.
A rule of thumb for what to look for
A row loop is a candidate for vectorising when each row's result depends only on that row's values, or on values you can compute for whole columns. Typical signs include:
foroverdf.iterrows()ordf.indexwith arithmetic in the body.ifandelseon a column value that sets another column.- A list that you
appendto and then assign back as a column. - A Python function applied to each value with
apply.
The following chapters take these in order: arithmetic first, then conditions, groups, shifted values and lookups.
Common mistakes at this stage
- Assuming a small test proves the loop is fine. Test with a realistic row count before deciding.
- Using
iterrowsto modify the DataFrame. The row you get is a copy, so writing to it does not changedf. You must assign back withdf.ator build a new column. - Timing only the loop body. If you build a list and then assign it to a column, include that step as well when comparing, because the vectorised version does it in the same expression.
- Rewriting without checking the result. A faster version that gives different numbers is a bug. The demo above compares the outputs with
np.allclose. Do the same for each rewrite.
Summary of the working model
- Python loops pay a fixed cost for every row: interpreter steps, object creation, boxing and label lookups.
- Column operations call compiled code once and work over contiguous typed arrays.
iterrowsis the most expensive loop form and also changes dtypes.- The gap grows with the number of rows, so measure on realistic sizes.
- Always confirm that a rewrite gives the same results as the original.
Exercise
A colleague writes for _, row in df.iterrows(): out.append(row["id"] * 2). The id column holds integers and the other columns hold floats. Name two separate problems with this code, and give the one-line vectorised replacement.
Show answer
First, it is slow because it builds a Series for every row and runs a Python loop body each time. Second, iterrows converts each row to a common dtype, so with mixed integer and float columns row["id"] becomes a float (for example 3.0 instead of 3), which can change the output and lose precision for large integers. The replacement is out = df["id"] * 2, which keeps the integer dtype and runs in compiled code.
Exercise
In the timing script, you change n from 100,000 to 1,000,000. Roughly what should you expect to happen to the loop time and to the vectorised time, and why does the ratio between them stay large?
Show answer
Both times grow with the row count, so the loop time rises by about ten times and the vectorised time by up to about ten times as well, though its fixed call cost is small. The ratio stays large because the loop pays a large constant cost for every row (Series creation, boxing, label lookups), while the vectorised version pays only a tiny per-element cost inside compiled code.