Skip to content

Applying Functions (apply, map, applymap)

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)

Use apply/map when you really need custom logic.

map transforms values in a single Series.

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 on Series
import pandas as pd
 
s = pd.Series([1, 2, 3, 4])
print(s.apply(lambda x: x * x))
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 apply is easy to write but can be slower for large data.

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))
  • Use vectorized operations if possible
  • Use map for simple value mapping (Series)
  • Use apply for custom logic on a Series or across rows/columns
  • Use applymap for element-wise transforms
diagram map, apply, applymap at a glance mermaid
map transforms one Series; apply works on a Series or DataFrame rows/columns; applymap runs map over every cell.

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”

Custom transforms often need to handle gaps in the data — continue to Handling Missing Data (isna, fillna, dropna).

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading