Sub topic 9
Element-wise changes with DataFrame.map and applymap
This chapter assumes you can write short Python functions and lambdas. It also assumes you can build a DataFrame, select columns, and assign results back to a DataFrame. You should already know Series.map and Series.apply from earlier chapters. Here you learn the one DataFrame method that works on single cells.
What DataFrame.map does
DataFrame.map(func) calls func once for every cell in the DataFrame. Each call receives one value, a scalar. The method returns a new DataFrame with the same index, the same columns and the same shape. Only the cell values change.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.map(lambda x: x * 10)) a b
0 10 30
1 20 40Any callable works: a lambda, a function you defined, a built-in such as len, or a bound method such as "${:.2f}".format. A string name such as "sum" is not accepted. That is a difference from DataFrame.apply.
import pandas as pd
prices = pd.DataFrame({"price": [1.5, 2.25, 3.0], "cost": [1.0, 1.75, 2.5]})
print(prices.map("${:.2f}".format)) price cost
0 $1.50 $1.00
1 $2.25 $1.75
2 $3.00 $2.50The original prices is unchanged. To keep the result, assign it to a name or write it back into the DataFrame.
map and applymap: one method, two names
Before pandas 2.1, the element-wise method was called DataFrame.applymap. In pandas 2.1 it was renamed DataFrame.map, so that the name matches Series.map. applymap still exists but is deprecated. Calling it emits a FutureWarning. The behavior is the same under both names.
Check your version before you pick a name:
import pandas as pd
print(pd.__version__)If your code must run on both old and new pandas, put the choice in one small helper:
import pandas as pd
def cellwise(df, func, **kwargs):
"""Apply func to every cell, on any pandas version."""
if hasattr(pd.DataFrame, "map"):
return df.map(func, **kwargs)
return df.applymap(func, **kwargs)
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(cellwise(df, lambda x: x + 1))In pandas versions before 2.1, df.map raises AttributeError. That is why the helper tests for the attribute and does not just call it. Once your minimum supported version is 2.1, drop the helper and call map directly.
The Styler object used for formatted output went through the same change. Styler.applymap is deprecated in favor of Styler.map.
What the function receives and must return
Two rules cover most uses.
- The function receives a single scalar value, never a row, a column or a list.
- The function should return a single value for each cell.
Internally, DataFrame.map goes through the columns one at a time and runs the function on each value in that column. Pandas then infers the dtype of each result column separately. So a column can change dtype even when the other columns do not. For example, an integer column can become a string column if your function returns strings.
Missing values and na_action
Missing values are cells holding NaN, None or NaT. They are passed to your function like any other value, so a function that cannot handle them fails. int(float("nan")) raises a ValueError, for instance. DataFrame.map accepts na_action="ignore", which skips missing cells and leaves them as they are.
import numpy as np
import pandas as pd
df = pd.DataFrame({"a": [1.5, np.nan], "b": [2.0, 3.0]})
print(df.map(int, na_action="ignore")) a b
0 1.0 2
1 NaN 3Column a becomes float64 because it still holds NaN. Column b has no missing values, so its results are integers. If you leave out na_action="ignore", the call raises ValueError as soon as it reaches the NaN.
Skipping missing cells keeps them missing. It does not fill them. To replace missing values, use fillna before or after the mapping.
Passing extra arguments
Extra keyword arguments given to DataFrame.map are forwarded to your function. A single function can then serve several purposes without a lambda wrapper.
import pandas as pd
def scale(x, factor, offset=0):
return x * factor + offset
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.map(scale, factor=10, offset=1)) a b
0 11 31
1 21 41Only keyword arguments are forwarded. The first positional slot is always the cell value.
Mixed dtypes: map only the columns you mean
DataFrame.map touches every column. A function written for strings fails when it reaches a number.
import pandas as pd
df = pd.DataFrame({"name": ["ann", "bob"], "score": [3, 4]})
# df.map(str.upper) raises TypeError: it reaches the integer column too.
text_cols = df.select_dtypes(exclude="number").columns
df[text_cols] = df[text_cols].map(str.upper)
print(df) name score
0 ANN 3
1 BOB 4Selecting by dtype, as above, keeps the code short. It also keeps working if you add more text columns later. For one column, df["name"].map(str.upper) is the more direct choice.
No dict lookup on a DataFrame
Series.map accepts a dict or a Series as a lookup table. DataFrame.map does not. It needs a callable. To recode values across a whole DataFrame, use DataFrame.replace:
import pandas as pd
df = pd.DataFrame({"a": ["y", "n"], "b": ["n", "y"]})
print(df.replace({"y": "yes", "n": "no"})) a b
0 yes no
1 no yesreplace leaves values that are not in the dict alone. Series.map with a dict turns them into NaN. Apart from the missing-key case, a dict lookup can be written as a function too: df.map(lookup.get) returns None for keys not in the dict. That makes replace the safer tool for a plain recode.
Choosing the right method
The table summarizes what each method passes to your function and what comes back.
| Method | Function receives | Typical result |
|---|---|---|
| `Series.map` | One element, or a dict/Series lookup | Series |
| `Series.apply` | One element | Series |
| `DataFrame.map` | One cell | DataFrame, same shape |
| `DataFrame.apply(axis=0)` | One whole column | Series or DataFrame |
| `DataFrame.apply(axis=1)` | One whole row | Series or DataFrame |
Use DataFrame.map when the same cell-level rule applies to every selected column. Examples are formatting numbers as text, cleaning strings across many columns, or flagging cells with a custom test. Use DataFrame.apply when the result for one cell depends on other cells in the same row or column.
Performance: map is a Python loop
DataFrame.map calls your Python function once per cell. A DataFrame with 200,000 rows and 5 columns means one million Python calls. Vectorized operations run in compiled code and avoid that overhead.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame(rng.normal(size=(200_000, 5)), columns=list("abcde"))
start = time.perf_counter()
slow = df.map(lambda x: x * 10)
t_map = time.perf_counter() - start
start = time.perf_counter()
fast = df * 10
t_vec = time.perf_counter() - start
print(slow.equals(fast))
print(f"map: {t_map:.3f}s, vectorized: {t_vec:.3f}s")The first line printed is True. The timings depend on your machine, but the vectorized version is usually faster by one to two orders of magnitude. Reach for a built-in before you write a lambda:
| Task | Instead of `df.map(...)` |
|---|---|
| Arithmetic on every cell | `df * 10`, `df + 1` |
| Round numbers | `df.round(2)` |
| Cap or floor values | `df.clip(lower=0, upper=100)` |
| Convert to text | `df.astype(str)` |
| Recode specific values | `df.replace({...})` |
| Keep or replace by condition | `df.where(df > 0, 0)` |
| Test every cell | `df > 0`, `df.isna()` |
String methods such as .str.upper() work on one column at a time. For many text columns, DataFrame.map(str.upper) on the selected subset is still a reasonable choice. There is no single DataFrame-wide .str accessor.
Pitfalls
- Forgetting to keep the result.
df.map(f)returns a new DataFrame. Writedf = df.map(f)or assign to a column subset. - Using
applymapin new code. It works but warns. Switch tomapon pandas 2.1 and later. - Passing a dict.
df.map({"a": "x"})fails because a DataFrame needs a callable. Usereplace. - Mixed dtypes. A string function applied to a numeric column raises
TypeError. Select columns first. - Unexpected dtype changes. Because dtypes are inferred per column, check
df.dtypesafter mapping, especially whenNaNforces an integer column to float. - Hand-written loops for cell logic across rows. If the result for a cell depends on its neighbors,
mapcannot see them. Useapply,shiftor a vectorized expression. - Assuming labels change. The index and the column names stay as they were. Use
renameto change labels.
Exercise
A DataFrame has the columns "city" (text) and "population" (integers). You run df.map(str.title) and get a TypeError. Why did it fail, and how do you fix it so only the city names change?
Show answer
DataFrame.map calls the function on every cell, so str.title was also called on the integers in "population", and str.title rejects a non-string. Select the text columns first and assign the mapped result back, for example: textcols = df.selectdtypes(exclude="number").columns; df[textcols] = df[textcols].map(str.title). For a single column, df["city"] = df["city"].map(str.title) also works.
Exercise
You have a DataFrame of floats with some NaN cells. You want to turn every cell into a rounded integer but keep the NaN cells as NaN. Write the call, and say which dtype a column with NaN ends up with.
Show answer
df.map(round, na_action="ignore") skips the NaN cells, so round is never called on them. A column that still contains NaN ends up as float64, because NaN is a float. Columns with no NaN become int64. If you do not need a custom function, df.round() does the same job without a Python loop, although it keeps float dtype.