Sub topic 3
Element-wise changes with `DataFrame.map` and `applymap`
Assume you know Python functions and lambdas, and can create, select, and assign pandas Series and DataFrame objects.
Element-wise changes with `DataFrame.map` and `applymap`
DataFrame.map calls a function once for every cell and returns a new DataFrame with the same shape. It is useful when the transformation depends only on one value.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
result = df.map(lambda value: value * 10)
print(result)In pandas versions before 2.1, the equivalent method is DataFrame.applymap. In pandas 2.1 and later, applymap is deprecated. Prefer map.
Controlling what `apply` returns
DataFrame.apply passes a complete column by default (axis=0) or a complete row with axis=1. The returned value controls the result shape.
| Function return | Typical result |
|---|---|
| Scalar | One result per input Series |
| Series | A combined DataFrame |
| List-like value | A Series containing those values |
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
summary = df.apply(
lambda column: pd.Series({"minimum": column.min(), "maximum": column.max()})
)
print(summary)When to avoid `apply`: vectorized alternatives
A vectorized operation applies an expression to an entire column using pandas or NumPy internals. It is usually shorter and faster than row-wise Python calls.
df = pd.DataFrame({"price": [10, 20], "quantity": [2, 3]})
df["total"] = df["price"] * df["quantity"]
print(df)Use axis=1 only when the logic genuinely needs several fields and has no clear vectorized equivalent.
> callout tip > Test the vectorized version first. Row-wise apply can become a bottleneck on large DataFrames.
Using `apply` with `groupby`
Grouped apply runs a function once for each group and combines the results.
df = pd.DataFrame({
"team": ["x", "x", "y", "y"],
"score": [3, 9, 4, 6],
})
spread = df.groupby("team")["score"].apply(lambda values: values.max() - values.min())
print(spread)Pitfalls and best practices
- Remember that
mapis cell-wise, whileapplyreceives a Series. - Handle missing values deliberately. A function such as
str.uppermay fail onNone; useSeries.map(..., na_action="ignore")when appropriate. - Check dtypes after custom functions. Mixed return values can produce an
objectdtype. - Keep grouped functions predictable and return consistent types.
- Avoid changing the DataFrame inside the function.
Exercise
Which method should transform every cell in a DataFrame independently?
Show answer
Use DataFrame.map. Use DataFrame.apply when the function needs a whole row or column.