Sub topic 7
map or apply: which one to use
This chapter assumes you can write Python functions and lambdas, build a pandas Series and DataFrame, and select columns and assign new ones. It compares Series.map and Series.apply, which look alike and often return the same result. It then gives a rule for choosing between them.
What the two methods share
Both methods call your function once for each element of a Series and return a new Series with the same index. For a plain function, the results are identical.
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.map(lambda x: x * 10))
print(s.apply(lambda x: x * 10))Both calls print 10, 20, 30. The differences appear when you go beyond a single function.
Where they differ
| Feature | `Series.map` | `Series.apply` |
|---|---|---|
| Accepts a function | Yes | Yes |
| Accepts a dict or Series for lookup | Yes | No |
| Extra arguments for the function | No (use a lambda) | Yes, as `*args` and `**kwargs` |
| `na_action="ignore"` | Yes | No |
| Works on a DataFrame | `DataFrame.map` (cell by cell) | `DataFrame.apply` (by column or row) |
map is specialized for element-wise translation. apply is the more general method. It forwards extra arguments, and it can take a function that returns a Series for each element, which map is not designed for.
Choosing a method
Use map when:
- You want to translate values with a dict or another Series.
- You want to skip missing values with
na_action="ignore". - The function takes one value and needs nothing else.
Use apply when:
- Your function needs extra parameters, such as a rate or a threshold.
- You need to work on whole rows or columns of a DataFrame with
axis.
The next example uses each method where it fits.
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
codes = pd.Series(["a", "b", "c"])
print(prices.apply(add_tax, rate=0.2))
print(codes.map({"a": "x", "b": "y"}))The first call passes rate=0.2 straight through apply. The second uses a dict, which only map accepts. Because "c" has no key in the dict, its result is NaN.
Decision flow
The first question matters most. Both methods run Python code once per element, so they are slow on large data. If an arithmetic expression or a built-in method such as s.str.upper() does the same job, use that instead. A later chapter covers vectorized alternatives in detail.
Common errors
- Passing a dict to
apply.Series.applyexpects a callable, so a dict raises an error. Usemapfor lookups. - Forgetting that
mapwith a dict returnsNaNfor missing keys. A value with no matching key does not stay unchanged. If you want to keep the original, uses.map(mapping).fillna(s). - Passing extra arguments to
map.maphas no**kwargsfor your function, so wrap the call in a lambda. - Expecting
na_actiononapply.Series.applyhas nona_actionparameter, so a function likestr.upperfails when it receivesNone. Usemap(..., na_action="ignore")instead.
Exercise
You have a Series grades = pd.Series(["A", "B", "C", "B"]) and a dict points = {"A": 4, "B": 3, "C": 2}. Which method converts the grades to points, and why? Then, which method would you use to apply def curve(score, bonus): return score + bonus with bonus=5 to a Series of scores?
Show answer
Use grades.map(points), because only map accepts a dict for lookup. For the curve function, use scores.apply(curve, bonus=5), because apply forwards extra keyword arguments to the function.
Exercise
A Series s = pd.Series(["a", None, "c"]) fails with s.apply(str.upper). Write a call that returns A, NaN, C without error.
Show answer
s.map(str.upper, na_action="ignore"). The na_action="ignore" option keeps missing values from being passed to str.upper, and they stay as missing in the result.