Sub topic 7
When apply, map, and string methods are the right tool
This chapter assumes you know basic Python, pandas Series and DataFrames, and the idea that NumPy operates on whole arrays at once. You have seen why row loops are slow and how to vectorize arithmetic. Now we look at the in-between tools: apply, map, and the .str methods. They are not vectorized in the NumPy sense, but they are often the correct choice. The goal is to know which one fits and what each one costs.
What apply and map really do
Series.apply(func) and Series.map(func) call a Python function once per element. The loop runs inside pandas, but each call to func is still a Python function call. There is no compiled inner loop doing the arithmetic.
This means s.apply(lambda x: x * 1.2) is usually much slower than s * 1.2. The second form hands the whole array to compiled code in one step.
DataFrame.apply(func, axis=1) is worse. For each row, pandas builds a new Series object and passes it to your function. That construction cost is paid 200,000 times for a 200,000-row frame. It is the same cost pattern as iterrows, hidden behind a nicer name.
| Tool | Calls Python per... | Typical use | Speed relative to a column expression |
|---|---|---|---|
| `s * 1.2`, `np.where` | nothing (compiled) | arithmetic, conditions | fastest |
| `s.map(dict)` | nothing per element (hash lookup) | recoding values | fast |
| `s.str.method()` | element, inside pandas | text cleanup | moderate |
| `s.apply(func)` | element | custom scalar logic | slow |
| `df.apply(func, axis=1)` | row, with a new Series per row | last resort | slowest |
Measure the gap
Run this to see the cost on your own machine. The numbers vary, but the order does not.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(200_000),
"qty": rng.integers(1, 10, 200_000),
})
start = perf_counter()
a = df.apply(lambda row: row["price"] * row["qty"], axis=1)
print(f"apply(axis=1): {perf_counter() - start:.3f}s")
start = perf_counter()
b = df["price"].apply(lambda x: x * 1.2)
print(f"Series.apply: {perf_counter() - start:.3f}s")
start = perf_counter()
c = df["price"] * 1.2
print(f"vectorized: {perf_counter() - start:.3f}s")Expect apply(axis=1) to be the slowest by a wide margin, Series.apply in the middle, and the column expression to be the fastest.
map for lookups
Series.map accepts a function, but it also accepts a dictionary or another Series. In that form it does a lookup, and no Python function is called per element.
import pandas as pd
codes = pd.Series(["N", "S", "N", "E", "S", "X"])
names = {"N": "North", "S": "South", "E": "East"}
regions = codes.map(names)
print(regions)Keys missing from the dictionary (here "X") become NaN. That is often what you want, since it makes unknown codes visible. If you want a default instead, chain fillna("Unknown").
Be careful with replace. Series.replace(dict) leaves unmatched values unchanged, while map(dict) turns them into NaN. Picking the wrong one is a common source of silent errors.
When you have many categories and the mapping is a table, a merge on the key column is also an option. For a small dictionary, map is simpler.
String methods
The .str accessor applies string operations across a column. Each method is implemented as a loop over Python string objects, so it is not as fast as numeric vectorization. It is still the right tool for text, for three reasons.
- It handles missing values.
s.str.lower()returnsNaNfor a missing entry. A barelambda x: x.lower()raisesAttributeErroronNaN. - It is shorter and easier to read than the equivalent
apply. - Many methods accept regular expressions and operate on the whole column in one call.
import pandas as pd
emails = pd.Series([" [email protected] ", "[email protected]", None, "[email protected]"])
clean = emails.str.strip().str.lower()
domain = clean.str.split("@").str[1]
is_example = clean.str.endswith("example.com")
print(pd.DataFrame({"clean": clean, "domain": domain, "is_example": is_example}))Chaining several .str calls is fine. Each call creates a new Series, so for very large columns you pay some memory, but the readability is usually worth it.
Regular expressions and the regex flag
Methods such as str.replace and str.contains take a regex argument. If you do not need a pattern, pass regex=False. A plain substring search avoids the regex engine and is faster.
import pandas as pd
s = pd.Series(["item-1", "item-2", "other", None])
has_item = s.str.contains("item", regex=False, na=False)
renamed = s.str.replace("item-", "#", regex=False)
print(has_item.tolist())
print(renamed.tolist())The na=False argument matters. Without it, contains returns NaN for missing entries, and using that result as a boolean filter raises an error.
Convert repeated strings first
A string column with few distinct values, such as city names, can be converted to the category dtype. The .str methods still work on it, and pandas can apply the operation to the unique values rather than every row. Chapter material on dtypes covers the memory side; here the point is that a repetitive text column is a case where converting first can speed up later string work.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
s = pd.Series(rng.choice(["oslo", "lima", "pune", "cairo"], size=500_000))
start = perf_counter()
upper_obj = s.str.upper()
print(f"object dtype: {perf_counter() - start:.3f}s")
cat = s.astype("category")
start = perf_counter()
upper_cat = cat.str.upper()
print(f"category dtype: {perf_counter() - start:.3f}s")Treat the result as something to measure, not a guarantee. The gain depends on your pandas version and how many distinct values you have.
When apply is the right tool
Use apply when the logic cannot be written as column arithmetic, a lookup, or a string method. Examples include parsing a custom format, calling a library function that accepts one scalar, or branching logic with many nested rules.
Follow these rules:
- Apply to a single column with
Series.apply, not to rows withaxis=1. - Pass only the columns you need.
df[["a", "b"]].apply(f, axis=1)builds smaller row objects thandf.apply(f, axis=1). - Keep the function small and free of work that could be done once outside it, such as compiling a regex or building a lookup table.
- Check whether the function is already vectorizable. Many
if/elsefunctions becomenp.whereornp.select.
import numpy as np
import pandas as pd
df = pd.DataFrame({"qty": [1, 4, 7, 12]})
def tier(q):
if q >= 10:
return "bulk"
if q >= 5:
return "mid"
return "small"
slow = df["qty"].apply(tier)
fast = pd.Series(
np.select([df["qty"] >= 10, df["qty"] >= 5], ["bulk", "mid"], default="small"),
index=df.index,
)
pd.testing.assert_series_equal(slow, fast)
print(fast.tolist())np.select takes a list of conditions and a list of results. It picks the first condition that is true for each row, so order the conditions from most specific to least. The assertion at the end is the habit from the previous chapter: prove the rewrite returns the same answer.
A row-wise apply is acceptable when the dataset is small (thousands of rows), when the code runs once, or when profiling shows it is not the bottleneck. Do not rewrite code that is not slow.
Common errors
- Using
apply(axis=1)for arithmetic. Replace it with a column expression. - Forgetting missing values in
.strchains. Usena=Falsein boolean methods and expectNaNin outputs. - Using
mapwith a partial dictionary and expecting unmatched values to stay. They becomeNaN. Usereplaceif you want them kept. - Calling
.stron a non-string column. A numeric column raisesAttributeError: Can only use .str accessor with string values. Convert withastype(str)first, and remember that this turnsNaNinto the text"nan". - Assuming
.stris as fast as arithmetic. It is a Python-level loop. If a string task dominates your profile, consider whether categories, a lookup, or earlier filtering reduces the work.
Exercise
A DataFrame has a column "status" with codes "A", "B", and "C", and some missing values. You want the labels "active", "blocked", and "closed". Missing and unknown codes should stay missing. Which tool do you use, and why not df.apply(axis=1)?
Show answer
Use df["status"].map({"A": "active", "B": "blocked", "C": "closed"}). Map with a dictionary does a lookup, so no Python function runs per element, and keys not in the dictionary (including NaN) become NaN, which is the required behavior. df.apply(axis=1) would build a Series for every row and call a Python function on each, which is far slower and does nothing the lookup cannot do.
Exercise
A function returns "high" when score > 90, "medium" when score > 60, and "low" otherwise. Rewrite it for a Series named score without apply, and say what you would run to confirm the result matches the original.
Show answer
Use np.select([score > 90, score > 60], ["high", "medium"], default="low"), wrapped in pd.Series(..., index=score.index). The most specific condition goes first because np.select takes the first match. Compare it with score.apply(originalfunction) using pd.testing.assertseries_equal.