Lambda Functions in Pandas
Write small one-line anonymous functions with lambda and use them inside apply, map, sort_values(key=), loc[] and groupby().agg().
Writing a full def function just to split a car name or add 10 runs feels heavy. In the car-pricing notebook, Munna extracts the brand with a one-liner: df["name"].apply(lambda x: x.split(" ")[0]). That lambda is a tiny function written inline, and it appears all over real pandas code.
Definition
A lambda function is a small anonymous (unnamed) function written in a single expression:
lambda arguments: expression. It takes any number of arguments, evaluates one expression, and returns its value automatically.
- Anonymous — it has no name of its own; you usually pass it straight into another function (
apply,map,sort_values). - One expression — no
returnkeyword, no multiple statements, no loops.if/elseis allowed only as a conditional expression:a if condition else b. - Same as def —
lambda x: x + 10behaves exactly likedef f(x): return x + 10.
Syntax
python
lambda arg1, arg2, ...: expression
# common pandas uses
s.apply(lambda x: ...) # per value
df.apply(lambda row: ..., axis=1) # per row
s.map(lambda x: ...) # per value
df.sort_values("col", key=lambda s: ...) # custom sort key (gets the whole column)
df.loc[lambda d: condition] # filter using the current DataFrame
df.assign(new=lambda d: ...) # new column from the current DataFrame
df.groupby("g")["c"].agg(lambda s: ...) # custom aggregation (gets each group's Series)| Part | Meaning |
|---|---|
lambda | keyword that starts an anonymous function |
arg1, arg2 | parameters, comma-separated (no brackets) |
: | separates parameters from the body |
expression | a single expression; its value is returned |
Example — lambda basics
python
add_ten = lambda x: x + 10
print(add_ten(5))
print((lambda a, b: a * b)(4, 6))text
15
24How it works: add_ten is a variable holding the function. The second line creates a lambda and calls it immediately with (4, 6). (Style guides prefer def when you need a named function — lambdas shine when passed inline.)
Example — lambda inside apply (first name, surname, label)
python
import pandas as pd
df = pd.DataFrame({
"name": ["Virat Kohli", "Rohit Sharma", "MS Dhoni", "Jasprit Bumrah", "Ravindra Jadeja"],
"team": ["RCB", "MI", "CSK", "MI", "CSK"],
"runs": [741, 417, 161, 12, 280],
"balls": [480, 300, 110, 15, 190],
})
print(df["name"].apply(lambda x: x.split(" ")[0]))
print(df["runs"].apply(lambda r: "Star" if r >= 400 else "Regular"))
print(df.apply(lambda row: round(row["runs"] / row["balls"] * 100, 1), axis=1))text
0 Virat
1 Rohit
2 MS
3 Jasprit
4 Ravindra
Name: name, dtype: str
0 Star
1 Star
2 Regular
3 Regular
4 Regular
Name: runs, dtype: str
0 154.4
1 139.0
2 146.4
3 80.0
4 147.4
dtype: float64How it works: the first lambda receives each name string and returns the first word — the same trick as extracting the car brand from "Maruti Swift Dzire VDI". The second uses a conditional expression. The third receives each row (because of axis=1) and computes the strike rate.
Example — lambda in sort, filter and groupby
python
print(df.sort_values("name", key=lambda s: s.str.split().str[-1]))
print(df.loc[lambda d: d["runs"] > 200])
print(df.groupby("team")["runs"].agg(lambda s: s.max() - s.min()))text
name team runs balls
3 Jasprit Bumrah MI 12 15
2 MS Dhoni CSK 161 110
4 Ravindra Jadeja CSK 280 190
0 Virat Kohli RCB 741 480
1 Rohit Sharma MI 417 300
name team runs balls
0 Virat Kohli RCB 741 480
1 Rohit Sharma MI 417 300
4 Ravindra Jadeja CSK 280 190
team
CSK 119
MI 405
RCB 0
Name: runs, dtype: int64How it works:
sort_values(key=...)— the lambda receives the whole column and returns the values to sort by (surnames: Bumrah, Dhoni, Jadeja, Kohli, Sharma).loc[lambda d: ...]— the lambda receives the DataFrame itself and returns a boolean mask. Very useful in method chains where the DataFrame has no variable name yet.agg(lambda s: ...)— the lambda receives each team's runs as a Series and returns one number (the range). RCB has only one player, so the range is 0.
What the lambda receives — cheat table
| Where | The lambda's argument is… |
|---|---|
s.apply(lambda x: ...), s.map(lambda x: ...) | one value |
df.apply(lambda col: ...) | one column (Series) |
df.apply(lambda row: ..., axis=1) | one row (Series) |
df.map(lambda x: ...) | one cell value |
df.loc[lambda d: ...], df.assign(c=lambda d: ...) | the whole DataFrame |
sort_values(key=lambda s: ...) | the whole column being sorted |
groupby(...).agg(lambda s: ...) | one group's Series |
Common mistakes
- ❌
lambda x: return x + 1✅lambda x: x + 1— noreturnkeyword. - ❌
lambda r: "Star" if r >= 400✅ a conditional expression needs anelse:"Star" if r >= 400 else "Regular". - ❌ Multi-line logic squeezed into one unreadable lambda. ✅ If you need
elif, several steps or comments, write adeffunction. - ❌
df["name"].apply(lambda x: x.split()[0])on huge data when a vectorised version exists. ✅df["name"].str.split().str[0]does the same job with the.straccessor.
Interview tip
Q: Can a lambda contain an if/elif/else?
A: Only as nested conditional expressions — lambda r: "A" if r >= 100 else ("B" if r >= 50 else "C"). It works but quickly becomes unreadable; for three or more branches a named def function (or np.select/pd.cut) is clearer.
Key points to remember
- A lambda is an anonymous one-expression function: lambda args: expression — the value is returned automatically.
- No return keyword, no statements; if/else only as a conditional expression (a if cond else b).
- Lambdas are mostly passed inline to apply, map, sort_values(key=), loc[], assign and groupby().agg().
- What the lambda receives depends on where it is used: a value, a row, a column, a group, or the whole DataFrame.
- df.loc[lambda d: ...] and assign(c=lambda d: ...) let you refer to the DataFrame inside a method chain.
- Use a def function when the logic needs several branches or steps — readability beats cleverness.
Try it yourself
Lambdas inside apply
Lambdas in sort, filter and groupby
Practice: car brand from the name
Revision Flashcards
Tap a card to flip it and see the answer.
