groupby and Pivot Tables
Aggregate data by category with groupby — the Pandas equivalent of Excel pivot tables
If I had to pick the one Pandas function that delivers the most business value — the one that shows up in nearly every real analysis I have ever built — it is groupby(). Not because it is fancy. Because it answers the question every manager asks: "How does this metric break down by category?"
Total sales by region. Average order value by product line. Number of active customers by city and quarter. Customer churn rate by acquisition channel. All of these are groupby() problems. One function, infinite applications.
I have seen analysts spend forty minutes building a pivot table in Excel to answer a question that groupby().agg() answers in four lines of Python. And when the manager asks "can you break it down by quarter too?" — the Excel analyst starts over. The Python analyst adds one line.
The mistake beginners make is calling groupby() and then not knowing what to do with the result. You almost always want three things after a groupby: multiple aggregations in the same call (.agg()), the index reset back to a regular column (.reset_index()), and a sort by the aggregated value. That combination — groupby().agg().reset_index().sort_values() — is the most useful chain in data analysis. Learn it until it is automatic.
Examples
Key Points
- ✓groupby().agg() with named aggregations is the cleanest syntax for multi-column summaries
- ✓Always reset_index() after groupby to get a flat, workable DataFrame
- ✓pivot_table() adds margins (grand totals) and handles duplicate combinations automatically
- ✓groupby preserves NaN by default — set dropna=False to include null keys in groups
- ✓For time series, groupby("Month") after extracting df["Month"] = df["Date"].dt.month
Practice Question
You want total Sales and average Margin, grouped by Region. Which groupby syntax is correct?