Sub topic 11
When to avoid apply: vectorized alternatives
This chapter assumes you can write Python functions and lambdas, create a pandas Series and DataFrame, and select columns and assign new ones. It builds on the earlier chapters about map and apply.
Why apply is often the slow choice
apply and map call your Python function once per element, row, or column. Each call carries Python interpreter overhead. A vectorized expression such as df["price"] * df["qty"] runs as one operation in compiled code over the whole column.
With axis=1, the cost is higher still. pandas builds a new Series for every row before calling your function. On a large DataFrame, this is often one to two orders of magnitude slower than the vectorized version.
Reach for apply when no vectorized form exists. Check for one first.
A row-wise apply and its vectorized form
This version multiplies two columns row by row.
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 in one expression.
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)Both print this table:
price qty total
0 10.0 1 10.0
1 20.0 2 40.0
2 30.0 3 90.0The vectorized form is shorter, and it is usually much faster. You can confirm this with %timeit in a notebook on a DataFrame with a million rows.
Common replacements
Many apply calls fall into a few patterns that have a built-in equivalent.
| Instead of | Use |
|---|---|
| `s.apply(lambda x: x * 2)` | `s * 2` |
| `df.apply(lambda r: r["a"] + r["b"], axis=1)` | `df["a"] + df["b"]` |
| `s.apply(lambda x: x.upper())` | `s.str.upper()` |
| `s.apply(lambda x: x.year)` on datetimes | `s.dt.year` |
| `s.apply(lambda x: 1 if x > 0 else 0)` | `(s > 0).astype(int)` |
| `s.apply(lambda x: "hi" if x > 5 else "lo")` | `np.where(s > 5, "hi", "lo")` |
| a chain of if/elif branches | `np.select(conditions, choices, default=...)` |
| `s.apply(lambda x: lookup[x])` | `s.map(lookup)` |
The last row still calls map, but with a dict. Dict lookups run inside pandas rather than in your Python function, so they are much faster than a lambda.
Conditional logic with numpy
Branching is the most common reason people write a row-wise function. np.where and np.select handle it without one.
import numpy as np
import pandas as pd
df = pd.DataFrame({"score": [35, 60, 82, 95]})
conditions = [df["score"] >= 90, df["score"] >= 70, df["score"] >= 50]
choices = ["A", "B", "C"]
df["grade"] = np.select(conditions, choices, default="F")
print(df)np.select checks the conditions in order and uses the first one that is true for each row. Rows that match none get the default value. The output is:
score grade
0 35 F
1 60 C
2 82 B
3 95 AWhen apply is still the right tool
Keep apply when the logic cannot be written as whole-column operations. Typical cases:
- The function calls a library that accepts one value at a time, such as a parser or an API client.
- Each row needs a loop or branching that depends on earlier steps in the same row.
- The function returns a Series per column, as in a column summary, and the data is small.
- The data is small enough that clarity matters more than speed.
Write the clearest correct version first. Switch to a vectorized form when profiling shows the call is a bottleneck.
Decision flow
Exercises
Exercise
Rewrite df["flag"] = df["amount"].apply(lambda x: "big" if x > 100 else "small") without apply.
Show answer
Use np.where: df["flag"] = np.where(df["amount"] > 100, "big", "small"). It evaluates the comparison on the whole column at once instead of calling a Python function for each value.
Exercise
A DataFrame has numeric columns a and b. Why is df["a"] + df["b"] usually faster than df.apply(lambda r: r["a"] + r["b"], axis=1)?
Show answer
The addition runs once over whole columns in compiled code. The apply version builds a Series for each row and calls a Python function once per row, which adds overhead on every row.