Sub topic 16
Choosing the Right Tool for Speed and Clarity
What this chapter assumes
You have read the earlier chapters on adding columns. You should know how to assign a column with df["name"] = ..., how np.where and np.select work, and what map, apply, .str, .dt, cut, and transform do. This chapter does not introduce new methods. It gives you a way to pick among the ones you already have.
The working model: three tiers
Most column-building methods fall into three tiers. The tier tells you how the work is executed, and that largely determines both speed and readability.
- Vectorized operations. Arithmetic, comparisons,
np.where, andnp.selecthand whole arrays to compiled NumPy code. One call processes every row. - Purpose-built pandas helpers.
.str,.dt,map,replace,pd.cut,pd.qcut,pd.to_numeric,pd.to_datetime, andgroupby().transform("sum")are written for one job each. Most of them are fast. The.strmethods are an exception, covered below. - Python-level loops.
Series.apply,DataFrame.apply(axis=1), list comprehensions, anditerrowscall a Python function once per element or per row. They are flexible and the slowest.
Move down a tier only when the tier above cannot express your logic.
Why vectorized code wins
A vectorized expression like df["price"] * df["qty"] loops in C, over contiguous memory, with no Python function-call overhead per row. It is also shorter to read, because the code states what you want and not how to iterate.
The script below times three ways to build columns on 100,000 rows. It runs as written.
import numpy as np
import pandas as pd
from timeit import timeit
rng = np.random.default_rng(0)
n = 100_000
df = pd.DataFrame({
"price": rng.uniform(1, 50, n),
"qty": rng.integers(1, 10, n),
})
def tier(p):
if p < 5:
return "low"
if p < 20:
return "mid"
return "high"
candidates = {
"vectorized total": lambda: df["price"] * df["qty"],
"apply axis=1 total": lambda: df.apply(
lambda r: r["price"] * r["qty"], axis=1
),
"np.select tier": lambda: np.select(
[df["price"] < 5, df["price"] < 20], ["low", "mid"], default="high"
),
"Series.apply tier": lambda: df["price"].apply(tier),
}
for name, fn in candidates.items():
seconds = timeit(fn, number=3) / 3
print(f"{name:22s} {seconds * 1000:9.2f} ms")Exact numbers depend on your machine and pandas version. The ordering is stable. The vectorized lines take a few milliseconds. Series.apply is typically tens of times slower. apply(axis=1) is usually the slowest because pandas builds a Series object for every row before calling your function. The gap grows with row count.
Where the tiers blur
Tier 2 helpers are not all equally fast, and a few details matter for your choice.
| Method | Execution | Practical note |
|---|---|---|
| `map` with a dict | Hash lookup | Fast. Unmatched keys become `NaN`. |
| `replace` with a dict | Value matching | Keeps unmatched values. More flexible, often slower than `map`. |
| `.dt` accessor | Vectorized on datetime64 | Fast, but only after `to_datetime`. |
| `.str` accessor | Python loop internally on object columns | Convenient and readable. Not truly vectorized. |
| `pd.cut` / `pd.qcut` | Vectorized binning | Returns a categorical column. |
| `transform("sum")` | Optimized groupby path | Fast when given a built-in name. |
| `transform(lambda ...)` | Python call per group | Slower, and the cost scales with the number of groups. |
Two points deserve emphasis. First, .str methods are still the right choice for cleaning text. They handle missing values for you and read clearly. Do not replace them with apply to "go faster", because that is slower and more fragile. Second, transform("sum") with a string name takes a fast path, while the same logic written as a lambda does not. Prefer the string name whenever one exists.
Clarity is a real criterion
Speed is not the only reason to choose. A readable chain is easier to review and to debug.
result = (
df
.assign(
total=lambda d: d["price"] * d["qty"],
tier=lambda d: np.select(
[d["price"] < 5, d["price"] < 20],
["low", "mid"],
default="high",
),
)
.assign(share=lambda d: d["total"] / d["total"].sum())
)
print(result.head())This chain is fully vectorized, each step has a name, and it never modifies df. Using assign() also sidesteps the copy and chained-assignment problems from the previous chapter, because you never write into a slice.
If a condition has several branches, name the pieces first. Named boolean masks let a reader understand the logic without decoding a long expression.
cheap = df["price"] < 5
bulk = df["qty"] >= 5
df["label"] = np.select(
[cheap & bulk, cheap, bulk],
["cheap bulk", "cheap", "bulk"],
default="standard",
)When `apply` is the right answer
apply is not a mistake. It is the correct tool when the logic cannot be expressed on whole columns. Typical cases:
- Parsing a structured string per row, such as a JSON blob or a custom format.
- Calling a third-party function that accepts only scalars.
- Logic with early exits or state that depends on the row's contents in a way masks cannot capture.
import json
events = pd.DataFrame({
"payload": ['{"user": "ann", "n": 3}', '{"user": "bob", "n": 5}'],
})
events["user"] = events["payload"].apply(lambda s: json.loads(s)["user"])
print(events)When you do use apply, apply it to the single column you need (df["col"].apply(...)) and not to the whole frame with axis=1. That avoids building a Series per row. Keep the function small and give it a name so it can be tested on its own.
The `np.where` gotcha: both branches always run
np.where(cond, a, b) evaluates a and b for every row first, then picks. Any error or warning inside either expression happens even for rows where that branch is not chosen.
d = pd.DataFrame({"a": [10.0, 5.0, 8.0], "b": [2.0, 0.0, 4.0]})
d["ratio"] = np.where(d["b"] != 0, d["a"] / d["b"], np.nan)
print(d)Pandas gives inf for the division by zero and the np.where replaces it, so this works. With integer NumPy arrays or functions like np.log, the unused branch can raise warnings or errors. Mask the input first, or use Series.where.
Common errors
- Using
apply(axis=1)for arithmetic. If your function only adds, multiplies, or compares columns, rewrite it as a column expression. - Using
iterrowsto fill a column. It is slow and loses dtypes, because each row becomes a Series with a common type. Use vectorized code orapplyon one column. - Optimizing before measuring. On 1,000 rows, any method finishes in milliseconds. Pick the clearest one. Use
timeitor%timeitwhen the data is large or the step runs often. - Rewriting
.stror.dtcalls as lambdas. The built-in accessors handleNaNand are easier to read. - Using a lambda in
transformwhen a name works.transform("mean")beatstransform(lambda s: s.mean()). - Expecting
mapto keep unmapped values. It returnsNaNfor them. Usereplace, or chain.fillna(df["col"]).
A short checklist
- Can the column be written as arithmetic or a comparison? Use a vectorized expression.
- Does it pick between values by condition? Use
np.whereornp.select. - Is it a lookup, a text clean-up, a date part, or a bin? Use
map,replace,.str,.dt, orcut. - Does it need a group total or mean on every row? Use
groupby().transform()with a built-in name. - Is none of this possible? Use
Series.applyon one column, and keep the function simple.
Exercise
A teammate writes df["discounted"] = df.apply(lambda r: r["price"] * 0.9 if r["qty"] >= 5 else r["price"], axis=1). Rewrite it so it is vectorized, and explain why the new version is faster.
Show answer
Use df["discounted"] = np.where(df["qty"] >= 5, df["price"] * 0.9, df["price"]). The condition and both prices are computed on whole columns in compiled code. The original calls a Python function and builds a Series for every row, which adds overhead that grows with the number of rows.
Exercise
You need a region_avg column holding each row's region mean of amount. Which call is preferred, transform("mean") or transform(lambda s: s.mean()), and why?
Show answer
Prefer df.groupby("region")["amount"].transform("mean"). Passing the built-in name lets pandas use its optimized groupby path, while the lambda calls Python once per group. Both give the same values aligned to the original rows.