Normalize with Transform
Advanced · Write the code · 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 lessonAdd a new column called pct_of_dept to df that shows each employee's salary as a percentage of their department's total salary. Round to 1 decimal place.
Print df[['name', 'department', 'pct_of_dept']].to_string(index=False).
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Carol', 'Dave'],
'department': ['Eng', 'Eng', 'Sales', 'Sales'],
'salary': [90000, 110000, 60000, 40000]
})
# Add pct_of_dept column using transform
More Pandas GroupBy exercises
- Basic GroupBy SumIntermediate
- Named AggregationAdvanced
- Predict the GroupBy OutputIntermediate
- Filter Groups by SizeAdvanced
- Multi-Column GroupByAdvanced
- Fix the GroupBy BugAdvanced
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz