0
0
Pandasdata~10 mins

apply() with lambda functions in Pandas - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - apply() with lambda functions
Start with DataFrame
Define lambda function
Call apply() on DataFrame/Series
apply() sends each element/row/column to lambda
Lambda processes element and returns result
apply() collects all results
Return new Series/DataFrame with results
apply() takes a lambda function and runs it on each element, row, or column of a DataFrame or Series, returning the processed results.
Execution Sample
Pandas
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
result = df['A'].apply(lambda x: x * 2)
print(result)
This code doubles each value in column 'A' using apply() with a lambda function.
Execution Table
StepInput to lambda (x)Lambda operationLambda outputResult Series state
111 * 220: 2
222 * 240: 2, 1: 4
3End of SeriesNo operationN/AFinal Series: [2, 4]
💡 All elements in Series 'A' processed; apply() returns new Series with doubled values.
Variable Tracker
VariableStartAfter 1After 2Final
xN/A12N/A
resultEmpty[2][2, 4][2, 4]
Key Moments - 2 Insights
Why does apply() return a new Series instead of modifying the original?
apply() creates a new Series with the results of the lambda function, leaving the original data unchanged, as shown in execution_table rows 1-3.
What does the lambda function receive as input during apply()?
The lambda receives each element of the Series one by one, as seen in execution_table column 'Input to lambda (x)'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the lambda output when x is 2?
A2
B4
C6
D8
💡 Hint
Check the row where Input to lambda (x) is 2 in the execution_table.
At which step does the result Series first contain the value 2?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Result Series state' column in the execution_table.
If the lambda was changed to 'lambda x: x + 1', what would be the final result Series?
A[3, 4]
B[1, 2]
C[2, 3]
D[4, 5]
💡 Hint
Add 1 to each original value in variable_tracker for 'x' after each step.
Concept Snapshot
apply() runs a lambda on each element of a Series or DataFrame.
Syntax: df['col'].apply(lambda x: operation)
Returns a new Series with results.
Original data stays unchanged.
Useful for quick element-wise transformations.
Full Transcript
We start with a DataFrame and want to change values in one column. We define a lambda function that doubles a number. Using apply(), we send each value in the column to the lambda. The lambda returns the doubled value. apply() collects these results into a new Series. The original column stays the same. This process is step-by-step shown in the execution table and variable tracker. Beginners often wonder why the original data doesn't change or what the lambda receives. The quiz questions help check understanding of these steps.