groupby and Pivot Tables in pandas
Aggregate and summarise data by categories — the most-used pandas operation in reporting
groupby is the pandas equivalent of SQL GROUP BY and Excel pivot tables. It groups rows by one or more columns and applies an aggregation function (sum, mean, count, etc.) to each group.
This is the operation data analysts use most in daily work — calculating total sales by region, average salary by department, order count by month. Mastering groupby makes you dramatically more productive.
Examples
Key Points
- ✓groupby().sum() / .mean() / .count() — the three most common aggregations
- ✓Use .agg() to apply multiple aggregations in one step and name the output columns
- ✓Always .reset_index() after groupby to get a clean flat DataFrame for further work
- ✓fill_value=0 in pivot_table fills missing combinations with 0 instead of NaN
- ✓margins=True adds a "Total" row and column to pivot tables
Practice Question
You want total Revenue AND order count by Region in one DataFrame. Which approach gives both in one step?