Performance Tips
pandas is fast when you let it work on whole columns, and slow when you treat a DataFrame like a list of Python objects. A few habits make the difference between a script that takes seconds and one that takes an hour. Timing numbers depend on the computer, so the examples here print comparisons rather than exact times.
1. Avoid Python loops over rows
iterrows() creates a new Series object for every single row. It's convenient but by far the slowest way to process data:
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(1)
df = pd.DataFrame({"qty": rng.integers(1, 10, 20_000),
"price": rng.random(20_000) * 20})
t0 = time.perf_counter()
totals = []
for _, row in df.iterrows():
totals.append(row["qty"] * row["price"])
loop_result = pd.Series(totals)
t1 = time.perf_counter()
vector_result = df["qty"] * df["price"]
t2 = time.perf_counter()
print("same values:", np.allclose(loop_result, vector_result))
print("vectorized at least 20x faster:", (t1 - t0) > 20 * (t2 - t1))same values: True
vectorized at least 20x faster: True
If you truly need a loop, itertuples() is much faster than iterrows(), but a vectorized expression beats both.
2. Replace if/else logic with vectorized choices
import numpy as np
import pandas as pd
temps = pd.Series([-3.0, 4.5, 12.0, 21.5, 30.2])
# slow style: temps.apply(lambda t: "freezing" if t < 0 else ...)
labels = np.select([temps < 0, temps < 15, temps < 25],
["freezing", "cool", "mild"], default="hot")
print(labels.tolist())
print(temps.where(temps > 0, 0).to_list()) # replace values <= 0 with 0
print(np.where(temps > 20, "warm", "not warm").tolist())['freezing', 'cool', 'cool', 'mild', 'hot']
[0.0, 4.5, 12.0, 21.5, 30.2]
['not warm', 'not warm', 'not warm', 'warm', 'warm']
3. Use the right dtypes
Smaller types mean less memory, and less memory means faster operations. Low-cardinality text columns benefit most from category:
import pandas as pd
n = 100_000
df = pd.DataFrame({
"country": ["Germany", "France", "Spain", "Italy"] * (n // 4),
"rating": [1, 2, 3, 4, 5] * (n // 5),
})
def mb(frame):
return round(frame.memory_usage(deep=True).sum() / 1_000_000, 2)
print("before:", mb(df), "MB")
slim = df.astype({"country": "category", "rating": "int8"})
print("after :", mb(slim), "MB")before: 3.88 MB
after : 0.2 MB
When reading a CSV, you can set the types up front with dtype={"country": "category"} and load only the columns you need with usecols=[...].
4. Build DataFrames once
Growing a DataFrame inside a loop copies all the data on every iteration. Collect plain Python rows first and create the frame at the end:
import pandas as pd
# Good: collect rows in a list, then build once
rows = []
for i in range(5):
rows.append({"id": i, "square": i * i})
df = pd.DataFrame(rows)
print(df.T)
# Even better: build the columns directly
df2 = pd.DataFrame({"id": range(5), "square": [i * i for i in range(5)]})
print(df.equals(df2)) 0 1 2 3 4
id 0 1 2 3 4
square 0 1 4 9 16
True
5. Use built-in methods over apply
Built-in aggregations and .str/.dt methods run in optimised code. Passing a Python lambda to groupby().apply() or agg() runs Python once per group:
import numpy as np
import pandas as pd
rng = np.random.default_rng(5)
df = pd.DataFrame({"shop": rng.integers(0, 200, 100_000),
"sales": rng.random(100_000)})
fast = df.groupby("shop")["sales"].mean()
slow = df.groupby("shop")["sales"].agg(lambda s: s.sum() / len(s))
print("same result:", np.allclose(fast, slow))
print("groups:", fast.size)same result: True
groups: 200
Quick checklist
| Habit | Why |
|---|---|
Vectorize: column arithmetic, np.where, np.select |
avoids per-row Python calls |
Avoid iterrows() and apply(axis=1) on big data |
each row becomes a Python object |
Use category, int8/int32, float32 where suitable |
less memory, faster scans |
Read only needed columns: usecols= |
less I/O and memory |
| Build frames once from lists/dicts | no repeated copying |
| Filter early in a chain | later steps process fewer rows |
Use .str, .dt, built-in aggregations |
compiled implementations |
Note: Don't optimise prematurely. For a few thousand rows, any approach is instant; choose the clearest code. These tips matter when you reach hundreds of thousands of rows or more.
Test yourself
Which is usually the slowest way to compute a new column?
- df["a"] * df["b"]
- np.where(df["a"] > 0, 1, 0)
- A for loop with df.iterrows()
- df["a"].clip(0)
What is the recommended way to build a DataFrame from data produced in a loop?
- pd.concat inside the loop for every row
- Append rows to a Python list, then call pd.DataFrame once
- df.loc[len(df)] = row inside the loop
- Write each row to a CSV file
Which dtype saves the most memory for a column with millions of rows but only 4 distinct country names?
- object
- string
- category
- float64