Editor

Named Aggregation

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

Use named aggregation to group df by region and compute:

  • total_revenue: sum of revenue
  • avg_units: mean of units
  • Print the resulting DataFrame.

    import pandas as pd
    df = pd.DataFrame({
    'region': ['North', 'South', 'North', 'South', 'North'],
    'revenue': [100, 200, 150, 250, 120],
    'units': [5, 10, 7, 12, 6]
    })
    # Use named aggregation

    More Pandas GroupBy exercises

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