We use apply() on columns to quickly change or analyze data in each column of a table.
apply() on columns in Pandas
DataFrame['column_name'].apply(function)The function can be a built-in function, a lambda (small anonymous function), or a custom function.
This applies the function to each value in the specified column.
df['age'].apply(lambda x: x + 1)
df['name'].apply(str.upper)
df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail')
This code creates a small table with names, ages, and scores. Then it uses apply() on columns to change ages, names, and scores as explained.
import pandas as pd data = {'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'score': [88, 45, 67]} df = pd.DataFrame(data) # Add 5 years to each age new_ages = df['age'].apply(lambda x: x + 5) # Convert names to uppercase upper_names = df['name'].apply(str.upper) # Mark scores as Pass or Fail pass_fail = df['score'].apply(lambda x: 'Pass' if x >= 50 else 'Fail') print('New ages:') print(new_ages) print('\nUppercase names:') print(upper_names) print('\nPass or Fail:') print(pass_fail)
If you want to change the column in the original table, assign the result back like df['age'] = df['age'].apply(...).
Using apply() is slower than vectorized operations but easier for custom logic.
apply() runs a function on each value in a column.
It helps change or analyze data quickly without loops.
You can use built-in, lambda, or your own functions with apply().
Practice
apply() function do when used on a pandas DataFrame column?Solution
Step 1: Understand the purpose of
Theapply()on columnsapply()method runs a function on each element of the column, transforming or analyzing the data.Step 2: Compare with other options
Deleting, sorting, or merging are not actions performed byapply()on a column.Final Answer:
It applies a function to each value in the column. -> Option AQuick Check:
apply()runs function on each column value [OK]
- Thinking apply() deletes or sorts data
- Confusing apply() with merge or drop functions
- Assuming apply() works on entire DataFrame without axis
df?Solution
Step 1: Identify correct method call syntax
The correct way to use apply on a column isdf['column'].apply(function). df['age'].apply(lambda x: x * 2) matches this.Step 2: Check lambda function usage
df['age'].apply(lambda x: x * 2) correctly passes a lambda function that doubles the value. Other options misuse syntax or assignment.Final Answer:
df['age'].apply(lambda x: x * 2) -> Option CQuick Check:
Use df['col'].apply(lambda x: ...) [OK]
- Using square brackets with apply like a list
- Assigning apply instead of calling it
- Calling apply as a standalone function
df below:score 0 10 1 20 2 30 3 40
What is the output of
df['score'].apply(lambda x: x // 15)?Solution
Step 1: Apply the lambda function to each value
Divide each score by 15 using floor division:
10 // 15 = 0
20 // 15 = 1
30 // 15 = 2
40 // 15 = 2Step 2: Write the resulting Series
The output Series is:
0 0
1 1
2 2
3 2Final Answer:
0 0 1 1 2 2 3 2 Name: score, dtype: int64 -> Option DQuick Check:
Floor division on each value = output [OK]
- Using normal division instead of floor division
- Misreading floor division results
- Confusing output format with DataFrame instead of Series
df['new_col'] = df['value'].apply(x: x + 5)
How can it be fixed?
Solution
Step 1: Identify syntax error in lambda function
The code usesx: x + 5without thelambdakeyword, which is required to define an anonymous function.Step 2: Correct the syntax
Addlambdabefore the function:df['value'].apply(lambda x: x + 5).Final Answer:
Missing lambda keyword; fix: df['value'].apply(lambda x: x + 5) -> Option AQuick Check:
Lambda keyword needed for inline functions [OK]
- Omitting the lambda keyword
- Using incorrect brackets or syntax for lambda
- Thinking apply() can't use inline functions
df with a column 'temperature' in Celsius. You want to create a new column 'temp_f' with Fahrenheit values using apply(). Which code correctly does this?Solution
Step 1: Recall the formula for Celsius to Fahrenheit
The correct formula is Fahrenheit = (Celsius * 9/5) + 32.Step 2: Check each option's lambda function
df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32) correctly applies the formula to each value in 'temperature'. df['temp_f'] = df.apply(lambda c: (c * 9/5) + 32) applies to whole DataFrame, C and D have incorrect formulas.Final Answer:
df['temp_f'] = df['temperature'].apply(lambda c: (c * 9/5) + 32) -> Option BQuick Check:
Use correct formula inside apply() on the column [OK]
- Applying function to whole DataFrame instead of column
- Mixing order of operations in formula
- Forgetting parentheses in formula
Ready to prove it?
Pass the test and this pattern moves unknown
