Sub topic 1
Why Looping Over Rows Is Slow
Prerequisites
You should know basic Python loops, functions, dictionaries, and pandas DataFrame and Series objects. You should also understand basic NumPy arrays.
Why looping over rows is slow
A pandas DataFrame stores data in columns. A row loop works against this design. With iterrows(), pandas builds a new Series for each row and performs Python-level work for every value. This creates overhead from object creation, indexing, and repeated function calls.
Column operations let pandas process many values in one operation. They often use optimized NumPy code internally, reducing Python overhead.
flowchart TD
A[DataFrame columns] --> B[Column expression]
B --> C[Optimized array operation]
D[iterrows loop] --> E[Python work for each row]
E --> F[More overhead]Replacing row arithmetic with column expressions
Assume that price and qty are numeric columns. A row loop calculates each total separately:
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 15.0],
"qty": [3, 1, 4],
})
totals = []
for _, row in df.iterrows():
totals.append(row["price"] * row["qty"])
df["total_loop"] = totals
df["total"] = df["price"] * df["qty"]
print(df)The expression df["price"] * df["qty"] multiplies corresponding values and preserves their index. It is shorter and usually much faster.
Measuring the speedup and verifying results
Measure equivalent operations rather than timing setup or printing. First compare the outputs, then use timeit:
import timeit
def with_loop(frame):
return pd.Series(
[row["price"] * row["qty"] for _, row in frame.iterrows()],
index=frame.index,
)
def with_columns(frame):
return frame["price"] * frame["qty"]
assert with_loop(df).equals(with_columns(df))
print(timeit.timeit(lambda: with_loop(df), number=100))
print(timeit.timeit(lambda: with_columns(df), number=100))The assert checks that the rewrite produces the same values and index. Timing depends on data size, pandas version, hardware, and data types.
::: callout note Vectorisation does not mean every operation runs in native code. It means expressing work as array or column operations so the library can avoid most Python-level iteration. :::
Boolean masks instead of if statements
A Boolean mask is a Series of True and False values. Use it to select rows or update a column:
df.loc[df["qty"] >= 3, "category"] = "bulk"
df.loc[df["qty"] < 3, "category"] = "single"This replaces an if statement inside a row loop. The conditions are evaluated for the whole column at once.
::: exercise Q: Rewrite df["total"] = df["price"] * df["qty"] as a row loop, then explain why the column expression is preferable. A: The loop reads each row and multiplies two values. The column expression performs the same aligned operation with less Python-level overhead. :::
::: estimate minutes: 12 :::