MODULE 4.1: GROUPBY MECHANICS & AGGREGATIONS

Master the foundational Split-Apply-Combine pattern in Pandas. Learn how to group data by single or multiple categorical keys, execute multi-metric aggregations, rename columns on the fly, and filter grouped subsets.

💡 The Split-Apply-Combine Paradigm

Data aggregation in Pandas revolves around three core steps: Splitting the data into groups based on some criteria, Applying a function (such as sum, mean, count, or custom logic) to each group independently, and Combining the results into a structured output dataframe or series.

1. Basic Groupby Sum & Mean Aggregation
Grouping retail transaction records by product category to compute total revenue and average quantity sold.
Python (groupby_basic.py)
import pandas as pd

def basic_groupby():
    data = {
        'Category': ['Electronics', 'Clothing', 'Electronics', 'Clothing', 'Furniture'],
        'Revenue': [1200, 450, 800, 300, 1500],
        'Units': [5, 12, 3, 8, 2]
    }
    df = pd.DataFrame(data)
    
    # Group by category and sum revenue
    summary = df.groupby('Category')['Revenue'].sum().reset_index()
    print("--- Total Revenue by Category ---")
    print(summary.to_string(index=False))

basic_groupby()
Output: --- Total Revenue by Category --- Category Revenue Clothing 750 Electronics 2000 Furniture 1500
2. Multi-Column Grouping (Hierarchical Keys)
Grouping sales data by multiple categorical columns (Region and Product Line) for granular regional performance analysis.
Python (groupby_multi.py)
import pandas as pd

def multi_groupby():
    data = {
        'Region': ['North', 'North', 'South', 'South', 'East', 'East'],
        'Product': ['Phone', 'Laptop', 'Phone', 'Laptop', 'Phone', 'Laptop'],
        'Sales': [5000, 12000, 4000, 9500, 6000, 14000]
    }
    df = pd.DataFrame(data)
    
    # Group by Region and Product
    grouped = df.groupby(['Region', 'Product'])['Sales'].sum().reset_index()
    print(grouped.to_string(index=False))

multi_groupby()
Output: Region Product Sales East Laptop 14000 East Phone 6000 North Laptop 12000 North Phone 5000 South Laptop 9500 South Phone 4000
3. Multi-Metric Aggregations (`.agg()`)
Applying multiple statistical functions (mean, sum, max) simultaneously across numeric columns for department salary analysis.
Python (groupby_multimetric.py)
import pandas as pd

def multimetric_agg():
    data = {
        'Department': ['IT', 'IT', 'HR', 'HR', 'Sales', 'Sales'],
        'Salary': [90000, 105000, 60000, 65000, 75000, 82000],
        'Bonus': [5000, 7000, 2000, 2500, 4000, 4500]
    }
    df = pd.DataFrame(data)
    
    # Compute mean and max for salary and bonus
    stats = df.groupby('Department').agg({
        'Salary': ['mean', 'max'],
        'Bonus': ['sum', 'mean']
    })
    print(stats)

multimetric_agg()
Output: Salary Bonus mean max sum mean Department HR 62500 65000 4500 2250.0 IT 97500 105000 12000 6000.0 Sales 78500 82000 8500 4250.0
4. Named Aggregations (`pd.NamedAgg`)
Generating clean, non-hierarchical column names directly within the `.agg()` method using Pandas Named Aggregations.
Python (named_agg.py)
import pandas as pd

def named_aggregation():
    data = {
        'Store': ['A', 'A', 'B', 'B', 'C', 'C'],
        'Revenue': [1000, 1500, 2000, 800, 1200, 1300]
    }
    df = pd.DataFrame(data)
    
    summary = df.groupby('Store').agg(
        Total_Rev=('Revenue', 'sum'),
        Avg_Rev=('Revenue', 'mean'),
        Max_Rev=('Revenue', 'max')
    ).reset_index()
    
    print(summary.to_string(index=False))

named_aggregation()
Output: Store Total_Rev Avg_Rev Max_Rev A 2500 1250.0 1500 B 2800 1400.0 2000 C 2500 1250.0 1300
5. Filtering Grouped Data (`.filter()`)
Filtering entire groups based on aggregate conditions (e.g., retaining only stores with total sales exceeding $3,000).
Python (groupby_filter.py)
import pandas as pd

def filter_groups():
    data = {
        'Store': ['StoreX', 'StoreX', 'StoreY', 'StoreY', 'StoreZ', 'StoreZ'],
        'Sale': [1500, 1800, 400, 500, 2000, 2500]
    }
    df = pd.DataFrame(data)
    
    # Keep rows only from stores whose total sales > 3500
    high_perf = df.groupby('Store').filter(lambda x: x['Sale'].sum() > 3500)
    print(high_perf.to_string(index=False))

filter_groups()
Output: Store Sale StoreX 1500 StoreX 1800 StoreZ 2000 StoreZ 2500
6. Transforming Grouped Data (`.transform()`)
Computing group-wise metrics (like department average salary) and broadcasting them back to match the original DataFrame shape for normalization.
Python (groupby_transform.py)
import pandas as pd

def transform_groups():
    data = {
        'Dept': ['Engineering', 'Engineering', 'Sales', 'Sales'],
        'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
        'Salary': [90000, 110000, 60000, 80000]
    }
    df = pd.DataFrame(data)
    
    # Broadcast department average salary to each employee row
    df['Dept_Avg_Salary'] = df.groupby('Dept')['Salary'].transform('mean')
    df['Diff_From_Avg'] = df['Salary'] - df['Dept_Avg_Salary']
    
    print(df[['Name', 'Dept', 'Salary', 'Dept_Avg_Salary', 'Diff_From_Avg']].to_string(index=False))

transform_groups()
Output: Name Dept Salary Dept_Avg_Salary Diff_From_Avg Alice Engineering 90000 100000.0 -10000.0 Bob Engineering 110000 100000.0 10000.0 Charlie Sales 60000 70000.0 -10000.0 Diana Sales 80000 70000.0 10000.0
7. Iterating Through Grouped Objects
Looping through grouped objects programmatically to inspect or export individual group dataframes.
Python (groupby_iterate.py)
import pandas as pd

def iterate_groups():
    data = {
        'Country': ['USA', 'USA', 'Canada', 'Canada'],
        'City': ['New York', 'Chicago', 'Toronto', 'Vancouver'],
        'Population': [8.4, 2.7, 2.9, 6.8]
    }
    df = pd.DataFrame(data)
    
    for country, group in df.groupby('Country'):
        print(f"=== Country: {country} ===")
        print(group[['City', 'Population']].to_string(index=False))
        print()

iterate_groups()
Output: === Country: Canada === City Population Toronto 2.9 Vancouver 6.8 === Country: USA === City Population New York 8.4 Chicago 2.7
8. Custom Aggregation Functions (`.agg(custom_func)`)
Passing a custom Python lambda function or user-defined function into `.agg()` to calculate custom statistical metrics (e.g., interquartile range).
Python (groupby_custom.py)
import pandas as pd

def custom_agg():
    data = {
        'Group': ['A', 'A', 'A', 'B', 'B', 'B'],
        'Score': [85, 90, 78, 92, 88, 95]
    }
    df = pd.DataFrame(data)
    
    # Custom range function: max minus min
    score_range = lambda x: x.max() - x.min()
    
    summary = df.groupby('Group')['Score'].agg(
        Mean='mean',
        Range=score_range
    ).reset_index()
    
    print(summary.to_string(index=False))

custom_agg()
Output: Group Mean Range A 84.3 12 B 91.7 7
9. Grouping by Binning Continuous Numerical Data
Combining `pd.cut()` with `groupby()` to segment continuous customer ages into age brackets and calculate spending behavior.
Python (groupby_bins.py)
import pandas as pd

def groupby_binned():
    data = {
        'Age': [22, 35, 41, 28, 55, 62, 44, 29],
        'Spend': [120, 350, 420, 180, 600, 750, 480, 200]
    }
    df = pd.DataFrame(data)
    
    # Bin ages into brackets: Young, Middle-Aged, Senior
    bins = [20, 35, 50, 100]
    labels = ['Young (20-35)', 'Middle (36-50)', 'Senior (51+)']
    df['Age_Group'] = pd.cut(df['Age'], bins=bins, labels=labels)
    
    summary = df.groupby('Age_Group')['Spend'].mean().reset_index()
    print(summary.to_string(index=False))

groupby_binned()
Output: Age_Group Spend Young (20-35) 170.00 Middle (36-50) 440.00 Senior (51+) 675.00
10. Handling Missing Group Keys (`dropna=False`)
Controlling whether missing values (`NaN`) in grouping columns are excluded or included as a distinct group using the `dropna` parameter.
Python (groupby_dropna.py)
import pandas as pd
import numpy as np

def groupby_missing_keys():
    data = {
        'Category': ['Tech', 'Tech', np.nan, 'Retail', np.nan],
        'Sales': [500, 700, 300, 400, 250]
    }
    df = pd.DataFrame(data)
    
    # Include NaN as an explicit group category
    summary = df.groupby('Category', dropna=False)['Sales'].sum().reset_index()
    print(summary.to_string(index=False))

groupby_missing_keys()
Output: Category Sales Retail 400 Tech 1200 NaN 550