Applying Functions (apply, map, applymap)
First: prefer vectorized operations
Pandas is fastest when you use vectorized operations.
Vectorized example
import pandas as pd
df = pd.DataFrame({"amount": [100, 200, 150]})
df["amount_with_tax"] = df["amount"] * 1.18
print(df)Vectorized example
import pandas as pd
df = pd.DataFrame({"amount": [100, 200, 150]})
df["amount_with_tax"] = df["amount"] * 1.18
print(df)Use applyapply/mapmap when you really need custom logic.
map()map() (Series only)
mapmap transforms values in a single Series.
Example: map categories
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))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 NaNNaN.
apply()apply() (Series or DataFrame)
Apply on a Series
apply on Series
import pandas as pd
s = pd.Series([1, 2, 3, 4])
print(s.apply(lambda x: x * x))apply on Series
import pandas as pd
s = pd.Series([1, 2, 3, 4])
print(s.apply(lambda x: x * x))Apply on rows (axis=1)
apply on rows
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)apply on rows
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 applyapply is easy to write but can be slower for large data.
applymap()applymap() (DataFrame element-wise)
Element-wise transform for the whole DataFrame.
applymap
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.applymap(lambda x: x * 10))applymap
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.applymap(lambda x: x * 10))Quick guidance
- Use vectorized operations if possible
- Use
mapmapfor simple value mapping (Series) - Use
applyapplyfor custom logic on a Series or across rows/columns - Use
applymapapplymapfor element-wise transforms
๐งช Try It Yourself
Exercise 1 โ Create a DataFrame
Exercise 2 โ Select a Column
Exercise 3 โ Filter Rows
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
