Skip to main content
Albero Academy

Performance

Vectorise, avoid iterrows, and use categories and query.

Applied Pandas9 min

Pandas is fast when you let it vectorise and slow when you loop. A few habits keep even large frames responsive — the biggest being: never iterate row by row if a vectorised operation exists.

Don't loop over rows

slow vs fast
# Slow — a Python loop over rows
for i, row in df.iterrows():
df.at[i, "total"] = row["price"] * row["qty"]
# Fast — vectorised
df["total"] = df["price"] * df["qty"]

Other wins

  • Convert repeated-string columns to category to cut memory.
  • Load only the columns you need (usecols=) and the right dtypes.
  • Use query() / vectorised masks instead of Python loops for filtering.
  • For data far bigger than RAM, reach for chunking or a tool like Polars/Dask.

Key takeaways

  1. 01Vectorise: column arithmetic, np.where, map and groupby run in C.
  2. 02Avoid iterrows and apply(axis=1) — they loop in Python and are far slower.
  3. 03category dtype and usecols/dtype at load time cut memory.
  4. 04For data bigger than RAM, use chunking or Polars/Dask.

Finished this chapter?

Mark it complete to track your progress through Pandas.