Lesson 8 of 9 · 25m
Profiling pandas: Copies, Vectorization, and Chunking
A practical performance workflow: measure the operation, remove Python loops, control copies, and chunk when data no longer fits the batch model.
pandas performance advice often degenerates into folklore: never use apply, always vectorize, copies are bad. Real engineering is less poetic. Measure the expensive operation, understand whether the bottleneck is Python-level iteration, memory traffic, sorting, or joining, then choose the smallest intervention that changes the scaling behavior.
Start with a profile, not a rewrite
%timeit df.groupby("customer_id")["amount"].sum()In scripts, use time.perf_counter around stages. In larger jobs, log rows, elapsed seconds, memory before/after, and output cardinality. Many "slow pandas" jobs are actually slow I/O, regex parsing, or JSON normalization. Rewriting the aggregation will not fix reading nested JSON row by row.
Replace row loops with column algebra
# slow: Python executes once per row
total = 0
for amount in df["amount"]:
total += amount
# vectorized: optimized native loop over contiguous arrays
total = df["amount"].sum()Vectorization means the loop still exists — it just happens inside compiled code over typed arrays. The same logic applies to string methods (df["email"].str.lower()), datetime accessors (.dt.dayofweek), comparisons, arithmetic, and cumulative operations.
apply is a spectrum
Series.apply with a NumPy-aware function can be acceptable. Row-wise df.apply(..., axis=1) is usually the expensive one because it materializes Python objects per row. Before reaching for it, look for np.where, np.select, map with a dictionary, str methods, or arithmetic combinations. If business logic truly is branchy and row-local, Python may be the right implementation — just do it in a typed batch framework or outside pandas intentionally.
Copies can dominate runtime
x = df.copy()
x = x.sort_values("created_at")
x = x.drop(columns=[...])Every step can allocate. Sometimes the fix is avoiding unnecessary copies; sometimes it is reducing columns so copies are smaller; sometimes it is using copy=False where safe. Do not remove copies blindly — use the ownership rules from earlier lessons. Correctness first, then memory.
Chunk when the batch no longer fits
chunks = []
for chunk in pd.read_csv("events.csv", chunksize=500_000, usecols=cols):
chunks.append(chunk.groupby("customer_id")["amount"].sum())
result = pd.concat(chunks).groupby(level=0).sum()Chunking works when the computation can be partially aggregated and recombined: sums, counts, min/max, approximate sketches. It does not transparently solve joins, global sorts, quantiles, or stateful deduplication. If the algorithm needs global visibility, chunking in pandas is often the point where SQL or a distributed engine is the honest answer.
Field notes
- Time stages separately: read, parse, join, aggregate, write.
- Row-wise
apply(axis=1)is the first thing to inspect in hot paths. - Memory traffic can cost more than CPU; smaller dtypes speed computation too.
- Concatenate once at the end, not repeatedly inside a loop.
- If every optimization makes the code less truthful, the execution model is wrong.
Was this lesson helpful?