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 — a Python loop over rowsfor i, row in df.iterrows():df.at[i, "total"] = row["price"] * row["qty"]# Fast — vectoriseddf["total"] = df["price"] * df["qty"]
Other wins
- Convert repeated-string columns to
categoryto 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
- 01Vectorise: column arithmetic, np.where, map and groupby run in C.
- 02Avoid iterrows and apply(axis=1) — they loop in Python and are far slower.
- 03category dtype and usecols/dtype at load time cut memory.
- 04For data bigger than RAM, use chunking or Polars/Dask.
