Sub topic 16
Choosing the right tool for speed and clarity
This chapter assumes you know df["col"] = ..., vectorized arithmetic, np.where/np.select, map, and apply. It gives you a way to pick among them.
Why the choice matters
Most column tasks can be done several ways. The methods differ in how much work happens in compiled code and how much in a Python loop. A vectorized operation runs one loop in compiled code across the whole column. apply(axis=1) calls your Python function once per row. On large frames the difference is often 10 to 100 times in running time.
Speed is only half the question. The best tool also states your intent in the fewest lines.
Measure the gap
This script builds the same column two ways and times both.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.uniform(1, 50, 200_000),
"qty": rng.integers(1, 10, 200_000),
})
start = time.perf_counter()
df["total_vec"] = df["price"] * df["qty"]
vec_time = time.perf_counter() - start
start = time.perf_counter()
df["total_apply"] = df.apply(lambda row: row["price"] * row["qty"], axis=1)
apply_time = time.perf_counter() - start
print(f"vectorized: {vec_time:.4f}s")
print(f"apply: {apply_time:.4f}s")
print(df["total_vec"].equals(df["total_apply"]))Exact times depend on your machine. The vectorized line is usually far faster, and both columns hold the same values.
A decision order
Work down this list and stop at the first option that fits.
- Arithmetic, comparisons, and boolean logic: use vectorized operators.
- Two or more outcomes based on conditions: use
np.whereornp.select. - Text or date work: use
.strand.dt. - Lookup from a dictionary: use
map(orreplaceto leave unmatched values unchanged). - Intervals: use
pd.cutorpd.qcut. - Group statistics per row: use
groupby().transform(). - Logic that truly needs Python, such as a call to a parsing library: use
apply.
When apply is the right answer
Use apply on a single column (Series.apply) when no built-in covers the logic. It is slower, but a clear function is better than an unreadable vectorized trick.
def shipping_label(weight):
if weight < 1:
return "letter"
if weight < 20:
return "parcel"
return "freight"
parcels = pd.DataFrame({"weight": [0.2, 5.0, 40.0]})
parcels["label"] = parcels["weight"].apply(shipping_label)
print(parcels)This particular rule would also work with np.select, which is faster. Prefer np.select once the frame is large or the code runs often.
Common mistakes
- Using
df.apply(..., axis=1)for arithmetic thatdf["a"] * df["b"]already does. - Writing a Python loop over
df.iterrows()to fill a column. It is slower thanapplyand harder to read. - Mixing types inside an
applyresult, which produces anobjectcolumn that later operations handle slowly.
Exercise
A frame has columns "score" (numbers) and "name" (text with extra spaces). You need a column "passed" that is True when score is at least 60, and a column "name_clean" with spaces stripped. Which tools do you use, and why not apply?
Show answer
Use the vectorized comparison df["passed"] = df["score"] >= 60 and the string accessor df["name_clean"] = df["name"].str.strip(). Both are built-in vectorized operations that run in compiled code and state the intent directly. apply(axis=1) would call a Python function per row, which is slower and longer.