Editor

Fix the GroupBy Bug

Advanced · Fix the bug · from Pandas GroupBy: Split-Apply-Combine for Powerful Aggregations

From the lesson: Pandas GroupBy: Split-Apply-Combine for Powerful Aggregations

Imagine you have a giant pile of receipts from a store. You want to know how much each department earned last month. What do you do? You sort the receipts into piles by department, add up each pile, and write down the totals.

Read the lesson

This code tries to add a column showing each row's deviation from its group mean, but it has a bug. Fix it so it works correctly.

The output should print the deviation column as a list, rounded to 1 decimal place each.

import pandas as pd
df = pd.DataFrame({
'group': ['X', 'X', 'Y', 'Y'],
'value': [10, 20, 100, 200]
})
# Bug: this line is wrong
df['deviation'] = df['value'] - df.groupby('group')['value'].mean()
print([round(x, 1) for x in df['deviation'].tolist()])

More Pandas GroupBy exercises

All Python exercises · 50 practice problems · Data Science & Machine Learning quiz