lambda with apply
A lambda is a tiny one-line function, perfect for quick apply and map calls.
In this page:
Syntax
df["column"].apply(lambda x: expression)
df.apply(lambda row: expression, axis=1)
lambda with apply
lambda x: expression defines an unnamed function inline. Combined with apply it lets you compute new columns from custom logic without writing a full def. For multi-step logic a named function is more readable.
Note:
Row-wise lambdas access columns by name, e.g. lambda r: r["a"] + r["b"].
Example: lambda with apply
import pandas as pd
df = pd.DataFrame({"name": ["ann", "bob"], "score": [82, 47]})
df["name"] = df["name"].apply(lambda s: s.title())
df["result"] = df["score"].apply(lambda x: "pass" if x >= 50 else "fail")
print(df)
# Output:
# name score result
# 0 Ann 82 pass
# 1 Bob 47 fail
Related Topics
Common Mistakes
- Writing long unreadable lambdas
- Forgetting axis=1 when using row values
- Using a lambda where np.where is simpler
Chapter Summary
- lambda is an inline function
- Works with apply and map
- Use axis=1 for rows
- Use def for complex logic
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: