Sub topic 1
Why Looping Over Rows Is Slow
Prerequisites
This chapter assumes you can do the following:
- Write basic Python, including functions, loops and dictionaries.
- Create and index a pandas DataFrame and Series.
- Recognise a NumPy array and know that pandas columns are built on them.
The working model
A DataFrame stores each column as one block of typed values, usually a NumPy array. A column of float64 is a contiguous run of 8-byte numbers. Pandas and NumPy can hand that whole block to compiled C code, which walks through the numbers without running any Python bytecode per element.
Vectorising means writing an operation on whole columns, so that this compiled code does the repeated work. A row loop does the opposite. Python's interpreter does the repeating, and it pays a fixed overhead on every pass.
Where the time goes
DataFrame.iterrows() is the usual way to loop over rows. For each row it does the following:
- Gathers one value from every column.
- Builds a new
Seriesobject, with its own index and dtype. - Returns the Series to your loop body.
Inside the body, row["price"] is a label lookup on that Series. It then returns a Python-level number. The multiplication runs as an ordinary Python operation. Finally append grows a list, and you convert the list back to a column.
Every one of those steps is small. Repeated for every row, they dominate the runtime, and the useful arithmetic is a tiny fraction of the cost.
Worked example
Both versions below compute a line total for each order.
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"]
print(df)The vectorised line has no loop, no temporary Series per row and no list to convert back. df["price"] * df["qty"] runs one multiplication across both arrays. It returns a new Series aligned to the same index.
On three rows you will not notice a difference. The gap appears as the row count grows, because the loop pays its overhead once per row. On large frames, the vectorised form is often tens to hundreds of times faster. The exact ratio depends on your machine and data, so measure it. A later chapter shows how.
A second cost: dtype changes
iterrows has a correctness gotcha as well as a speed cost. A Series holds one dtype. When a row mixes floats and integers, pandas upcasts the values to a common type. In the example above, qty becomes 3.0 inside row. With strings or dates in the frame, the row becomes object dtype, and every value is boxed as a Python object.
Vectorised column operations keep each column's own dtype. This is faster and avoids surprises such as integers turning into floats.
Common errors
- Assuming the loop is fine because the code is short. Cost scales with the number of rows, not the lines of code.
- Growing a list and assigning it back. It works, but it is the pattern to replace. The column expression usually replaces all of it.
- Trusting a timing on tiny data. Test with realistic row counts.
- Believing
apply(axis=1)fixes this. It still calls Python once per row. A later chapter covers its cost.
Exercise
A DataFrame has float columns price and discount (a fraction between 0 and 1) and an integer column qty. Write one line that creates a column net equal to price times qty times (1 minus discount) without a loop. Then name two reasons the iterrows version would be slower.
Show answer
df["net"] = df["price"] * df["qty"] * (1 - df["discount"]). The loop version is slower because it builds a new Series for every row, and because each multiplication runs in the Python interpreter instead of in one compiled pass over the column arrays. It would also upcast qty to float inside each row.