Real-world data questions require segment-level analytics: "What is the average transaction size per user region?", "How does each employee's salary compare to their departmental median?" GroupBy, Transform, and Pivot Tables provide the operational toolkit to answer these questions.
| Mode | Method | Output Dimensions | Canonical Example |
|---|---|---|---|
| Aggregation | .agg() |
Collapsed (1 row per group). | Total department budget: df.groupby('dept')['salary'].sum() |
| Transformation | .transform() |
Preserved (original row count). | Group z-score: (salary - mean_dept) / std_dept |
| Filtering | .filter() |
Subset of original rows. | Keep only departments with 10+ employees. |
import pandas as pd
import numpy as np
# Sample transaction dataset
df = pd.DataFrame({
'region': ['East', 'West', 'East', 'North', 'West', 'East', 'North', 'West'],
'rep': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Henry'],
'sales': [450, 720, 310, 890, 640, 520, 410, 930],
'quarter': ['Q1', 'Q1', 'Q2', 'Q1', 'Q2', 'Q1', 'Q2', 'Q2']
})
# 1. Advanced Aggregations with Named Aggregations
rep_summary = df.groupby('region').agg(
total_sales=pd.NamedAgg(column='sales', aggfunc='sum'),
avg_sales=pd.NamedAgg(column='sales', aggfunc='mean'),
rep_count=pd.NamedAgg(column='rep', aggfunc='count')
)
print("--- Named Aggregations ---\n", rep_summary)
# 2. Group Transformation: Difference from Regional Mean
df['regional_mean'] = df.groupby('region')['sales'].transform('mean')
df['diff_from_mean'] = df['sales'] - df['regional_mean']
print("\n--- Transformed DataFrame ---\n", df[['region', 'rep', 'sales', 'diff_from_mean']])
# 3. Pivot Table: Total Sales by Region across Quarters
pivot_matrix = df.pivot_table(
values='sales',
index='region',
columns='quarter',
aggfunc='sum',
fill_value=0,
margins=True # Adds total 'All' row and column
)
print("\n--- Pivot Table Matrix ---\n", pivot_matrix)
To convert wide pivot tables back to clean long format for statistical visualization, run: pd.melt(df, id_vars=['region'], value_vars=['Q1', 'Q2'], var_name='quarter', value_name='sales').
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
Review basic indexing, boolean masking, and column selections.
Benchmark Pandas GroupBy vs Polars parallel multi-threaded aggregation.
Compare SQL grouping and pivot tables with Pandas .pivot_table().
Use grouping and aggregations to uncover segment patterns during EDA.