Sub topic 11
When to avoid apply: vectorized alternatives
This chapter assumes you can write simple Python functions and lambdas. It also assumes you can select columns and assign new ones in pandas, and that you have seen Series.map, Series.apply and DataFrame.apply in earlier chapters. Here you will learn why row-wise apply is often the slowest way to do a job, which built-in tools replace it, and how to recognize the cases where apply is still the right choice.
Why apply is slow
A pandas column is stored as a typed array, such as 64-bit floats in contiguous memory. Built-in operations like df["a"] * df["b"] hand the whole array to compiled code, which multiplies all the values in one pass. This is called vectorization.
apply and map cannot do that. They call your Python function once per element, per column or per row. Each call has overhead: the interpreter runs your function and boxes the value into a Python object. With DataFrame.apply(..., axis=1) the cost is higher still. pandas has to build a new Series object for every row, and that includes copying the values and creating an index.
For 10 rows the difference is invisible. For hundreds of thousands of rows it is often 10 to 100 times, or more.
Replacing a row-wise apply
The classic case is a calculation across columns. The row-wise version looks natural:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["total"] = df.apply(lambda row: row["price"] * row["qty"], axis=1)
print(df)The vectorized version gives the same result and is shorter:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["total"] = df["price"] * df["qty"]
print(df)You can measure the gap on your own machine. The exact numbers depend on your hardware and pandas version, but the ratio is large:
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 200_000
df = pd.DataFrame({
"price": rng.uniform(1, 100, n),
"qty": rng.integers(1, 10, n),
})
start = time.perf_counter()
slow = df.apply(lambda row: row["price"] * row["qty"], axis=1)
t_apply = time.perf_counter() - start
start = time.perf_counter()
fast = df["price"] * df["qty"]
t_vec = time.perf_counter() - start
print(f"apply: {t_apply:.3f}s, vectorized: {t_vec:.5f}s")
print("same values:", slow.equals(fast))Always check that both versions produce the same values before you switch. A speedup is worthless if the result changed.
A decision path
Ask these questions in order before you reach for apply.
Common replacements
Most apply calls fall into a few patterns. The table maps each one to a vectorized form.
| Task | Slow pattern | Vectorized form |
|---|---|---|
| Arithmetic on columns | `df.apply(lambda r: r["a"] + r["b"], axis=1)` | `df["a"] + df["b"]` |
| Text cleanup | `s.apply(lambda x: x.strip().title())` | `s.str.strip().str.title()` |
| Two-way condition | `s.apply(lambda x: "hi" if x > 5 else "lo")` | `np.where(s > 5, "hi", "lo")` |
| Several conditions | `s.apply(grade_function)` | `np.select(conditions, choices, default=...)` |
| Limit to a range | `s.apply(lambda x: min(max(x, 0), 100))` | `s.clip(0, 100)` |
| Membership test | `s.apply(lambda x: x in allowed)` | `s.isin(allowed)` |
| Value lookup | `s.apply(lambda x: table.get(x))` | `s.map(table)` |
| Date parts | `s.apply(lambda d: d.year)` | `s.dt.year` |
| Group range | `g.apply(lambda s: s.max() - s.min())` | `g.max() - g.min()` |
Text methods
The .str accessor runs string operations on a whole column. It also skips missing values instead of raising an error, which removes the need for na_action in many cases.
import pandas as pd
names = pd.Series([" Ada ", "grace", None])
print(names.str.strip().str.title())The None stays as a missing value in the output, and the other two entries are cleaned.
Conditions with np.where and np.select
An if/else inside a lambda becomes np.where(condition, value_if_true, value_if_false). Both branches are computed for the whole column, so they must be valid for every row.
When there are more than two outcomes, np.select takes a list of boolean conditions and a list of results. It checks the conditions in order, and the first one that is true wins. Rows that match no condition get default.
import numpy as np
import pandas as pd
df = pd.DataFrame({"score": [95, 82, 67, 45]})
conditions = [df["score"] >= 90, df["score"] >= 80, df["score"] >= 60]
df["grade"] = np.select(conditions, ["A", "B", "C"], default="F")
print(df)Because the order matters, put the strictest condition first. If you list >= 60 before >= 90, a score of 95 would get a "C".
For binning numbers into labeled ranges, pd.cut is another built-in option. It works on bin edges, so you don't write the conditions yourself.
Grouped summaries
Calling apply on a group runs your function once per group. That is usually fine when there are few groups. When the summary is something pandas already provides, use it directly. It runs in compiled code and is easier to read.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
g = df.groupby("team")["score"]
print(g.max() - g.min())The result matches g.apply(lambda s: s.max() - s.min()). It computes two fast aggregations and then subtracts two small Series.
Speeding up apply when you must keep it
Sometimes the logic really is custom. Before you give up on speed, there are a few cheaper options.
- Work on one column, not rows.
df["price"].apply(f)is much cheaper thandf.apply(f, axis=1), because no row Series are built. If your function uses only one or two columns, select those columns first. - Use
raw=True.df.apply(func, axis=1, raw=True)passes plain NumPy arrays instead of Series. This skips the row-building cost, but you lose labels. Inside the function you index by position, such asrow[0]. - Use a dict for lookups.
s.map(some_dict)is faster thans.map(lambda x: some_dict[x]), and missing keys becomeNaNinstead of raising aKeyError. - Avoid
np.vectorizeas a speed fix. Its documentation says it is provided for convenience and not for performance. It is essentially a Python loop.
When apply is the right tool
Do not treat apply as a mistake. It is the correct choice when no vectorized form exists:
- Parsing a string with a library call, for example
s.apply(json.loads). - Logic that depends on many columns and branches in ways that would need dozens of nested conditions.
- A function that returns a whole
Seriesor object per row or per group. - Small data, where the running time does not matter and readability does.
A short, clear apply on 500 rows beats an unreadable chain of masks. Pick the faster tool when the data is big or the job runs repeatedly. In other cases, choose the clearer code.
Pitfalls
- Comparing different results. A vectorized replacement can differ at the edges. Missing values behave differently:
NaN > 5isFalse, sonp.where(s > 5, "hi", "lo")labels a missing value "lo". Decide how missing values should be handled and add the check explicitly, for example withs.isna()as an extra condition innp.select. - Chained
.stron non-text columns..strraises anAttributeErrorwhen the column holds numbers. Convert first withastype(str)if that is what you want, but note that this turns missing values into the text"nan"in older pandas versions. - Mutating inside apply. A function that changes global state or the DataFrame being processed gives results that are hard to predict. Keep functions pure: they should return a value and change nothing else.
- Optimizing without measuring. Time the real data with
time.perf_counteror%timeit. If theapplystep takes 20 milliseconds, rewriting it is not worth the effort. - Both branches run.
np.whereandnp.selectevaluate every condition and choice for every row. An expression likenp.where(df["b"] != 0, df["a"] / df["b"], 0)still divides by zero in the rows you wanted to skip. pandas turns that intoinforNaNwithout raising an error, but the unused values are still computed. The final output is correct becausenp.wherediscards them.
Exercise
A DataFrame has a numeric column "tempc". You want a new column "label" with "cold" for values below 10, "mild" for values from 10 up to but not including 25, and "hot" for 25 and above. A colleague wrote df["tempc"].apply(lambda t: "cold" if t < 10 else ("mild" if t < 25 else "hot")). Rewrite it with a vectorized tool and say why the new version is faster.
Show answer
Use np.select: df["label"] = np.select([df["tempc"] < 10, df["tempc"] < 25], ["cold", "mild"], default="hot"). The conditions are checked in order, so the second one only decides rows that are 10 or above, and the default covers 25 and above. It is faster because the comparisons run once over the whole array in compiled code, instead of the interpreter calling a Python lambda for every element. One difference to note: a missing temperature gives "hot" here, because both comparisons are False. The lambda gives "hot" as well, so the results match, but you should add a df["temp_c"].isna() condition if you want a different label.
Exercise
You need to turn a column of JSON strings into Python dicts. Is a vectorized alternative available, and which method should you use?
Show answer
No built-in vectorized method parses JSON strings into Python objects, so Series.apply (or Series.map) with json.loads is the right tool: df["parsed"] = df["raw"].apply(json.loads). Select only that one column, not whole rows, to keep the overhead low. If the column has missing values, use map with na_action="ignore" so json.loads is not called on them.