Applying Functions (apply, map, applymap)
First: prefer vectorized operations
Section titled “First: prefer vectorized operations”Pandas is fastest when you use vectorized operations.
import pandas as pd
df = pd.DataFrame({"amount": [100, 200, 150]})
df["amount_with_tax"] = df["amount"] * 1.18
print(df)Use apply/map when you really need custom logic.
map() (Series only)
Section titled “map() (Series only)”map transforms values in a single Series.
Example: map categories
Section titled “Example: map categories”import pandas as pd
s = pd.Series(["pune", "delhi", "mumbai"])
state_map = {"pune": "MH", "delhi": "DL", "mumbai": "MH"}
print(s.map(state_map))If a value is missing from the map, it becomes NaN.
apply() (Series or DataFrame)
Section titled “apply() (Series or DataFrame)”Apply on a Series
Section titled “Apply on a Series”import pandas as pd
s = pd.Series([1, 2, 3, 4])
print(s.apply(lambda x: x * x))Apply on rows (axis=1)
Section titled “Apply on rows (axis=1)”import pandas as pd
df = pd.DataFrame({
"name": ["Asha", "Ravi"],
"score": [88, 91],
"bonus": [5, 2],
})
def final_score(row):
return row["score"] + row["bonus"]
df["final"] = df.apply(final_score, axis=1)
print(df)Row-wise apply is easy to write but can be slower for large data.
applymap() (DataFrame element-wise)
Section titled “applymap() (DataFrame element-wise)”Element-wise transform for the whole DataFrame.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.applymap(lambda x: x * 10))Quick guidance
Section titled “Quick guidance”- Use vectorized operations if possible
- Use
mapfor simple value mapping (Series) - Use
applyfor custom logic on a Series or across rows/columns - Use
applymapfor element-wise transforms
Visualize it
Section titled “Visualize it”flowchart LR A["Series.map(fn)"] --> R1["New Series, same shape"] B["Series/DataFrame.apply(fn)"] --> R2["Scalar, Series, or DataFrame"] C["DataFrame.applymap(fn)"] --> R3["New DataFrame, every cell transformed"]
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Map Values With a Dictionary
Section titled “Exercise 1 – Map Values With a Dictionary”Exercise 2 – Apply a Custom Function to a Series
Section titled “Exercise 2 – Apply a Custom Function to a Series”Exercise 3 – Apply Row-Wise With axis=1
Section titled “Exercise 3 – Apply Row-Wise With axis=1”Custom transforms often need to handle gaps in the data — continue to Handling Missing Data (isna, fillna, dropna).
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading