← Back to Pandas Course | Chapter 6: Data Operations | Lesson 4 of 7

lambda with apply

A lambda is a tiny one-line function, perfect for quick apply and map calls.

In this page:

  1. lambda with apply
Syntax
python
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

python
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
  1. Writing long unreadable lambdas
  2. Forgetting axis=1 when using row values
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.