We use apply() with lambda functions to quickly change or calculate new values for each item in a column or row of a table.
apply() with lambda functions in 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.
df['age_plus_10'] = df['age'].apply(lambda x: x + 10)
df['name_upper'] = df['name'].apply(lambda x: x.upper())
df['is_adult'] = df['age'].apply(lambda x: x >= 18)
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.
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)
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.
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.
Practice
apply() function with a lambda do in pandas?Solution
Step 1: Understand the purpose of apply() with lambda
Theapply()method lets you run a function on each element or row/column of a DataFrame or Series.Step 2: Recognize what lambda does
Alambdais a small anonymous function used insideapply()to specify what to do with each element.Final Answer:
It applies a small function to each element in a DataFrame column or row. -> Option BQuick Check:
apply() + lambda = element-wise function [OK]
- Thinking apply() sorts data
- Confusing apply() with merge or join
- Believing apply() creates new DataFrames
apply() with a lambda on a pandas Series named data to double each value?Solution
Step 1: Recall correct lambda syntax in Python
Python lambda functions use the formatlambda x: expression, solambda x: x * 2is correct.Step 2: Check apply() usage on Series
The method call isdata.apply(lambda x: x * 2). Other options have syntax errors or wrong order.Final Answer:
data.apply(lambda x: x * 2) -> Option AQuick Check:
Correct lambda syntax = data.apply(lambda x: x * 2) [OK]
- Using arrow syntax (=>) from other languages
- Missing colon after lambda parameter
- Calling apply() as a standalone function
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3]})
df['B'] = df['A'].apply(lambda x: x + 5)
print(df)What is the output?
Solution
Step 1: Understand the lambda function applied
The lambda adds 5 to each value in column 'A'. So 1+5=6, 2+5=7, 3+5=8.Step 2: Check DataFrame after assignment
Column 'B' gets these new values, while 'A' remains unchanged.Final Answer:
A B 0 1 6 1 2 7 2 3 8 -> Option CQuick Check:
Original + 5 = New column [OK]
- Mixing up columns A and B
- Forgetting to add 5 inside lambda
- Expecting error from correct syntax
df['C'] = df['A'].apply(lambda x x * 3)
Solution
Step 1: Check lambda function syntax
Python lambda requires a colon after parameters:lambda x: x * 3. The code misses the colon.Step 2: Understand error cause
Missing colon causes a syntax error, so code won't run.Final Answer:
Missing colon after lambda parameter causes syntax error. -> Option AQuick Check:
lambda syntax error = missing colon [OK]
- Forgetting colon after lambda parameter
- Thinking apply() can't be used on columns
- Assuming new columns must exist before assignment
df with a column 'score' containing numbers. You want to create a new column 'grade' that says 'Pass' if the score is 50 or more, and 'Fail' otherwise. Which code correctly uses apply() with a lambda to do this?Solution
Step 1: Understand conditional expression in lambda
Python usesvalue_if_true if condition else value_if_falsesyntax inside lambda.Step 2: Check application target and syntax
Applying to the Seriesdf['score']withlambda x: 'Pass' if x >= 50 else 'Fail'is correct, asxis each scalar score. Applying to the wholedf(withoutaxis=1) passes column Series to lambda, wherex['score']causes KeyError. Syntaxes like? :ternary orif-thenare invalid in Python.Final Answer:
df['grade'] = df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail') -> Option DQuick Check:
Correct if-else in lambda = df['grade'] = df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail') [OK]
- Using ?: ternary operator from other languages
- Applying lambda on whole DataFrame without axis
- Writing if-else without proper Python syntax
Ready to prove it?
Pass the test and this pattern moves unknown
