Fix the apply() Bug
Advanced · Fix the bug · from Pandas apply(), map(), transform(): Custom Data Transformations
From the lesson: Pandas apply(), map(), transform(): Custom Data Transformations
Pandas gives you dozens of built-in methods like .sum(), .mean(), and .str.upper(). But what happens when you need to run your own custom logic on every row, column, or cell? That is where apply(), map(), and transform() come in.
Read the lessonThis code tries to create a total column that sums math and science scores for each student using apply(). But it gives wrong results because of a missing argument. Fix the bug.
Print the total column as a list.
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'math': [90, 80],
'science': [85, 95]
})
# Bug: this produces wrong results
df['total'] = df[['math', 'science']].apply(lambda row: row['math'] + row['science'])
print(df['total'].tolist())
More Pandas Apply and Transform exercises
- Map Values with a DictionaryIntermediate
- Row-Level ApplyAdvanced
- Predict the map() OutputIntermediate
- Element-wise DataFrame FormattingAdvanced
- Refactor apply() to VectorizedAdvanced
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz