Sub topic 9
Element-wise changes with DataFrame.map and applymap
This chapter assumes you can write basic Python functions and lambdas, build a pandas DataFrame, and select columns. It also assumes you have seen Series.map from earlier chapters.
What DataFrame.map does
DataFrame.map calls your function once for every cell in the DataFrame. It passes a single value each time, and it returns a new DataFrame with the same index, the same columns, and the same shape. It is the DataFrame counterpart of Series.map with a function.
Use it when one rule applies equally to every cell, such as rounding all numbers or formatting every value as text.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
# pandas 2.1 and later
print(df.map(lambda x: x * 10))
# earlier versions: df.applymap(lambda x: x * 10)The output is a DataFrame with the values 10, 20, 30 and 40. The original df is unchanged. Assign the result to a variable or back to the DataFrame if you want to keep it.
map and applymap are the same operation
Before pandas 2.1, the element-wise method was called DataFrame.applymap. From pandas 2.1 the method is called DataFrame.map, and applymap is deprecated. Calling applymap on a recent version still works but emits a FutureWarning.
| pandas version | Method to use | Notes |
|---|---|---|
| Before 2.1 | `DataFrame.applymap` | `DataFrame.map` does not exist |
| 2.1 and later | `DataFrame.map` | `applymap` is deprecated and warns |
If your code must run on both old and new versions, check for the method instead of the version number:
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
elementwise = df.map if hasattr(df, "map") else df.applymap
print(elementwise(lambda x: x + 1))If you control the environment, upgrade and use DataFrame.map.
Missing values with na_action
DataFrame.map accepts na_action="ignore", as Series.map does. Missing values are then left as they are and are not passed to your function. This matters when the function would fail on None or NaN.
import pandas as pd
df = pd.DataFrame({"name": ["ann", None], "city": ["oslo", "rome"]})
print(df.map(str.title, na_action="ignore"))Without na_action="ignore", str.title(None) raises a TypeError.
Passing extra arguments
Extra keyword arguments given to DataFrame.map are forwarded to your function. This lets you reuse one function with different settings.
import pandas as pd
df = pd.DataFrame({"a": [1.234, 2.345], "b": [3.456, 4.567]})
print(df.map(round, ndigits=1))How it relates to DataFrame.apply
DataFrame.apply passes whole columns (or rows) to your function. DataFrame.map passes single values. The call count differs too: for a DataFrame with 1,000 rows and 5 columns, map calls your function 5,000 times.
Common errors
- Using it on a subset of columns by accident.
df.maptouches every column. If only some columns should change, select them first and assign back:df[["a", "b"]] = df[["a", "b"]].map(func). - Applying a function that fails on mixed dtypes. A function like
str.upperfails on numbers. Becausemapvisits every cell, one numeric column in a mostly text DataFrame raises an error. Select the text columns first. - Expecting a Series back. The result is always a DataFrame, even if your function returns a single type.
- Reaching for
mapwhen a vectorized method exists.df.round(1)is shorter and faster thandf.map(round, ndigits=1). Usemapwhen no built-in operation expresses the rule.
Exercise
A DataFrame has numeric columns "price" and "tax" and a text column "label". You call df.map(lambda x: x * 2). What happens to the "label" column, and how would you double only the numeric columns?
Show answer
The function runs on every cell, including text. Doubling a string repeats it (for example "ab" becomes "abab"), so the label column changes without an error, which is probably not what you want. To double only the numeric columns, select them and assign back: df[["price", "tax"]] = df[["price", "tax"]].map(lambda x: x * 2). A vectorized form, df[["price", "tax"]] * 2, is faster still.
Exercise
You run code containing df.applymap(len) on pandas 2.2 and see a FutureWarning. What is the fix?
Show answer
Replace applymap with map: df.map(len). The behavior is identical.