Editor

Multi-Column GroupBy

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 lesson

Group df by both region and product, then compute the sum of revenue. Reset the index and print the resulting DataFrame using .to_string(index=False).

import pandas as pd
df = pd.DataFrame({
'region': ['East', 'East', 'West', 'West', 'East', 'West'],
'product': ['A', 'B', 'A', 'B', 'A', 'A'],
'revenue': [100, 200, 150, 250, 120, 180]
})
# Group by region and product, sum revenue, reset index

More Pandas GroupBy exercises

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