Last updated
Applying Functions
Definition: Sometimes you need to transform every value in a column. Pandas offers built-in string methods, and apply to run your own function on each value.
Example 1 — built-in string methods
import pandas as pd
df = pd.DataFrame({"name": ["sam", "alex", "jo"]})
df["upper"] = df["name"].str.upper()
df["length"] = df["name"].str.len()
print(df)
Example 2 — apply your own function
import pandas as pd
df = pd.DataFrame({"price": [10, 20, 30]})
def add_tax(p):
return p * 1.2
df["with_tax"] = df["price"].apply(add_tax)
print(df)
Example 3 — apply with a lambda
import pandas as pd
df = pd.DataFrame({"score": [55, 80, 95]})
df["grade"] = df["score"].apply(lambda s: "Pass" if s >= 60 else "Fail")
print(df)
💡 Tip: prefer built-in methods (like .str.upper() or * 1.2) when they exist — they are faster than apply. Use apply for custom logic.
Try it Yourself
Output
Ad · responsive