Why Is My pandas Loop So Slow? iterrows vs Vectorize
About this lesson
Why is your pandas loop slow? Because it's a loop. Pandas was built to operate on whole columns at once, not one row at a time. New users see a DataFrame, see something that looks like a spreadsheet, and reach for for row in df.iterrows() — which works on a hundred rows, takes a quarter of a second on twenty-eight thousand, and takes minutes on a million. The fix is one line. This tutorial measures the same calculation three ways on the same 28,000-row OHLC table. The textbook anti-pattern iterrows — Series per row, slowest possible. The right-escape-hatch itertuples — named tuples, about ten times faster. And vectorize — drop the loop entirely, operate on whole columns, push the work down to NumPy and from there to C. Same answer. Over a thousand times faster. What You'll Build: - pandas_loop.py — compute daily return on a 28k-row prices table three ways. Measure each with time.perf_counter. Print the speed ratio at the end. - The iterrows pattern — for idx, row in df.iterrows(): row["Close"]. Works. Slow. Wraps each row in a Series, allocates a dict, pays for it on every row. 278 ms on 28k rows. - The itertuples upgrade — for row in df.itertuples(index=False): row.Close. Same loop shape, no Series wrapping, ~10x faster. Use it when you genuinely need a row-by-row walk that can't be expressed column-wise. - The vectorize pattern — df["ret"] = (df["Close"] - df["Open"]) / df["Open"]. No loop. NumPy under the hood, C under that. 0.26 ms on the same 28k rows. Over a thousand times faster than iterrows. - The mental shift — pandas is for whole-column operations. Boolean masks, arithmetic on Series, pandas built-ins like pct_change and rolling all vectorize automatically. If you find yourself writing a for loop over a DataFrame, there's usually a one-line column expression that replaces it. Timestamps: 0:00 - Intro — Why is your pandas loop slow? 0:22 - Preview — three strategies, same answer 1:07 - Open pandas_loop.py in nvim 1:23 - Method 1 — iterrows, the textbook
DeepCamp AI