0
0
Pandasdata~5 mins

apply() with lambda functions in Pandas

Choose your learning style9 modes available
Introduction

We use apply() with lambda functions to quickly change or calculate new values for each item in a column or row of a table.

You want to add 10 to every number in a list of ages.
You need to change all names in a list to uppercase letters.
You want to create a new column based on a simple rule from existing columns.
You want to check if values in a column meet a condition and mark them True or False.
Syntax
Pandas
DataFrame['column_name'].apply(lambda x: expression_using_x)

The lambda x: part means 'for each item x in the column'.

The expression after the colon is what you want to do with each item.

Examples
Adds 10 to each value in the 'age' column and saves it in a new column 'age_plus_10'.
Pandas
df['age_plus_10'] = df['age'].apply(lambda x: x + 10)
Changes all names to uppercase letters.
Pandas
df['name_upper'] = df['name'].apply(lambda x: x.upper())
Creates a True/False column showing if age is 18 or more.
Pandas
df['is_adult'] = df['age'].apply(lambda x: x >= 18)
Sample Program

This code creates a small table with names and ages. Then it adds 5 to each age, makes names uppercase, and checks if each person is an adult (18 or older). Finally, it prints the updated table.

Pandas
import pandas as pd

data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [17, 22, 15]}
df = pd.DataFrame(data)

# Add 5 years to each age
df['age_plus_5'] = df['age'].apply(lambda x: x + 5)

# Make names uppercase
df['name_upper'] = df['name'].apply(lambda x: x.upper())

# Check if person is adult
df['is_adult'] = df['age'].apply(lambda x: x >= 18)

print(df)
OutputSuccess
Important Notes

Lambda functions are small, quick functions you write inside apply().

Use apply() when you want to change or check each item in a column easily.

Summary

apply() with lambda lets you quickly change or check each value in a column.

You write a small function with lambda x: to say what to do with each item.

This is useful for simple calculations, text changes, or condition checks on data.