Pandas is fast when used the vectorised way and slow when used like a Python loop. This chapter is the handful of habits that keep it quick, the techniques for data that strains memory, and honest guidance on when a bigger tool is the right call.
Vectorise, never iterrows
# Slow: a Python loop over rowstotal = 0for _, row in df.iterrows():total += row["price"] * row["qty"]# Fast: vectorised (often 100×+ quicker)total = (df["price"] * df["qty"]).sum()
Reading big files
Don't load more than you need — select columns, set dtypes, and stream in chunks when a file won't fit:
# Only the columns you need, with efficient dtypespd.read_csv("big.csv", usecols=["date", "sales"],dtype={"sales": "float32"}, parse_dates=["date"])# Stream a huge file in chunks and aggregate as you gototal = 0for chunk in pd.read_csv("huge.csv", chunksize=100_000):total += chunk["sales"].sum()
query & eval
For large frames, query and eval evaluate expressions efficiently and can avoid big intermediate objects:
df.query("sales > 1000 and region == 'West'") # no boolean intermediatesdf.eval("revenue = price * qty", inplace=True) # compute without temporaries
When to leave pandas
Pandas holds everything in RAM. Past that, other tools take over — and it's a strength to know when:
- Polars — a much faster DataFrame library with a similar API, great on a single big machine.
- Dask — pandas-like API that parallelises across cores and larger-than-memory data.
- DuckDB — run SQL directly over files/DataFrames, very fast for analytics.
- Spark — distributed processing across a cluster for truly massive data.
Practice
Take an iterrows loop and rewrite it as a single vectorised expression; note the difference. Read a CSV with usecols and explicit dtypes and compare memory. Aggregate a large file with chunksize streaming. Name one dataset size where you'd move off pandas and to what.
Key takeaways
- 01Vectorise — avoid iterrows; it is orders of magnitude slower than column operations.
- 02Read lean: usecols, explicit dtypes and parse_dates cut memory and time.
- 03chunksize streams a file too big for memory so you can aggregate incrementally.
- 04query and eval evaluate expressions efficiently and avoid large intermediates.
- 05Past RAM, reach for Polars, Dask, DuckDB or Spark — knowing when is part of the skill.
