Sub topic 7
map or apply: which one to use
This chapter assumes you can write Python functions and lambdas. It also assumes you can build a Series or DataFrame and assign a new column. It compares Series.map and Series.apply and shows where DataFrame.apply and DataFrame.map fit. The aim is to let you pick the right method quickly and avoid its usual errors.
Why the choice matters
Series.map and Series.apply look interchangeable. Given a plain function, they produce the same result:
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.map(lambda x: x * 10).tolist())
print(s.apply(lambda x: x * 10).tolist())Both lines print [10, 20, 30]. Both call your function once per element in a Python loop. The differences show up in what else each method accepts, what it can return, and how it treats missing values.
What each method accepts
Series.map takes a function, a dict, or another Series. Series.apply takes a function (or a function name as a string) and passes extra arguments through to it.
| Feature | `Series.map` | `Series.apply` |
|---|---|---|
| Accepts a function | Yes | Yes |
| Accepts a dict or Series as a lookup table | Yes | No |
| `na_action="ignore"` to skip missing values | Yes | No |
| Extra arguments passed to your function | Wrap it in a lambda or `functools.partial` | Yes, `args=` and keyword arguments |
| Function may return a Series to create columns | Not useful | Yes, result becomes a DataFrame |
| Always one output value per input value | Yes | No, the output can expand into columns |
Read the table as a set of capabilities. If your task needs a lookup, only map can do it. If your task needs extra parameters or several output columns, apply is the better fit. If neither applies, the two are equivalent.
Lookups belong to map
When the transformation is "replace each value by its entry in a table", pass the table to map:
import pandas as pd
codes = pd.Series(["US", "DE", "US", "FR"])
names = {"US": "United States", "DE": "Germany"}
print(codes.map(names))0 United States
1 Germany
2 United States
3 NaN
dtype: objectValues with no matching key become NaN. This is the most common surprise with dict mapping. You have two ways to keep the original value instead:
import pandas as pd
codes = pd.Series(["US", "DE", "US", "FR"])
names = {"US": "United States", "DE": "Germany"}
filled = codes.map(names).fillna(codes)
replaced = codes.replace(names)
print(filled.tolist())
print(replaced.tolist())Both lines print ['United States', 'Germany', 'United States', 'FR']. Use replace when unmatched values should stay as they are. Use map when an unmatched value is a signal you want to see as NaN, for example to count how many codes your table does not cover.
A dict lookup is faster than a function call per element. The lookup runs inside pandas rather than calling your Python code for every row. When a task can be written as a lookup, prefer it over a function.
A Series works as a lookup table too. Its index supplies the keys and its values supply the results:
import pandas as pd
codes = pd.Series(["US", "DE", "FR"])
table = pd.Series({"US": "United States", "DE": "Germany", "FR": "France"})
print(codes.map(table).tolist())This prints ['United States', 'Germany', 'France']. It is useful when the lookup table already lives in a Series, for example one loaded from a file with index_col.
Missing values: map can skip them
map has an na_action parameter. With na_action="ignore", missing values are not passed to your function. You can see this by counting the calls:
import numpy as np
import pandas as pd
calls = []
def record(x):
calls.append(x)
return x
s = pd.Series([1.0, np.nan, 3.0])
s.map(record)
print(len(calls))
calls.clear()
s.map(record, na_action="ignore")
print(len(calls))The first count is 3 and the second is 2. This matters for functions that fail on missing data. str.upper raises an error when it receives NaN, because NaN is a float and not a string. Series.apply has no na_action, so with apply you must handle missing values inside the function, for example with pd.isna(x), or filter first.
Extra arguments belong to apply
apply forwards keyword arguments to your function, so one function can serve several calls:
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.apply(add_tax, rate=0.25).tolist())This prints [12.5, 25.0, 37.5]. Positional extras go in a tuple: prices.apply(add_tax, args=(0.25,)).
With map, bind the extra argument yourself:
import functools
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.map(functools.partial(add_tax, rate=0.25)).tolist())
print(prices.map(lambda p: add_tax(p, 0.25)).tolist())Both lines print [12.5, 25.0, 37.5]. This is a minor inconvenience. It is rarely a reason to choose apply on its own.
Result shape: apply can add columns
map returns one value per input value. apply can turn each element into several values by returning a Series, and the result becomes a DataFrame:
import pandas as pd
s = pd.Series(["Ada Lovelace", "Alan Turing"])
parts = s.apply(lambda name: pd.Series(name.split(), index=["first", "last"]))
print(parts) first last
0 Ada Lovelace
1 Alan TuringIf your function returns a list instead, apply gives you a Series whose elements are lists. Only a returned Series is expanded into columns.
For this specific task, s.str.split(expand=True) is shorter and faster. The .str accessor covers most string work, and .dt covers dates. Check for a built-in accessor method before writing a function.
A decision path
The questions below settle most cases. Ask them in order.
The first question comes first because it protects you from the largest cost. Any function-per-element call runs at Python speed, whichever method you pick. The next chapters cover vectorized alternatives in detail.
Related methods on a DataFrame
The same names exist on DataFrames, and they differ from the Series versions.
| Method | Function receives | Typical use |
|---|---|---|
| `Series.map(f)` | One element | Transform or look up one column |
| `Series.apply(f)` | One element | Same, plus extra arguments or Series results |
| `DataFrame.apply(f)` | One column (Series) | Per-column summaries |
| `DataFrame.apply(f, axis=1)` | One row (Series) | Logic that uses several columns |
| `DataFrame.map(f)` | One cell | Same function on every cell |
DataFrame.map was called applymap before pandas 2.1. applymap still works in 2.x but emits a deprecation warning. Use map on a DataFrame only when the same function is meaningful for every column. A function that formats numbers will fail or give nonsense on a text column.
Common errors
- Using
mapwith a dict and forgetting theNaNfor unmatched keys. Check withresult.isna().sum()after mapping. - Passing a dict to
apply.applyexpects a function. Usemapfor lookups. - Calling
str.upperon a column with missing values. Usemap(..., na_action="ignore"), or.str.upper(), which handles missing values for you. - Expecting
mapto expand into columns. It does not. Useapplyreturning a Series, or an accessor such as.str.split(expand=True). - Using row-wise
applywhere a column expression works.df.apply(lambda r: r["a"] + r["b"], axis=1)is the same asdf["a"] + df["b"], and the second form is shorter and much faster.
Summary of the choice
Prefer a vectorized expression or an accessor when one exists. Use map for lookups and for functions that must skip missing values. Use apply when the function needs extra arguments or returns a Series. For plain element-wise functions the two behave the same, so choose whichever reads better in your code.
Exercise
You have a column grade with values "A", "B", "C" and some missing values. You want the numbers 4, 3, 2 for the grades and want missing grades to stay missing. Which method do you use, and what code does it?
Show answer
Use Series.map with a dict, because this is a lookup: df["points"] = df["grade"].map({"A": 4, "B": 3, "C": 2}). Missing grades are not keys in the dict, so they become NaN, which is the result you want. Grades outside A, B and C also become NaN, so check df["points"].isna().sum() against the number of missing grades if you need to catch typos.
Exercise
A function discount(price, pct) returns price * (1 - pct / 100). Write one line with apply and one line with map that apply a 15 percent discount to the Series prices.
Show answer
With apply: prices.apply(discount, pct=15). With map: prices.map(lambda p: discount(p, 15)), or prices.map(functools.partial(discount, pct=15)) after import functools. Both give the same values. apply forwards the keyword argument itself, while map needs a lambda or partial to bind pct.
Exercise
You run s.apply(lambda name: pd.Series(name.split(), index=["first", "last"])) on a Series of two-word names, and then s.map with the same lambda. What is the difference in the result, and which built-in method could replace the apply version?
Show answer
apply expands each returned Series into a row, so the result is a DataFrame with columns first and last. map returns one value per element, so each cell holds a whole Series object and no columns are created. The built-in alternative is s.str.split(expand=True), which returns a DataFrame with integer column names and is faster.