Module 5 · Pandas: Your Data Workbench · Lesson 17 of 51

Summaries: groupby, agg and pivot tables

Split, apply, combine; several statistics at once with agg; pivot tables and crosstabs; ranking, percent of total and grouping by month.

In this lesson · about 45 minutes

  • Answer 'per something' questions with groupby
  • Compute several statistics at once with named aggregations
  • Build pivot tables and crosstabs, and group dates by month

Try it · data lab

Split, apply, combine: groupby step by step

Pick a grouping column and a calculation, then step through what pandas does behind one line of code.

pandas

orders.groupby("branch")["total"].sum()
#order_idbranchtotal
01001Riverside3.5
11002Downtown12
21003Riverside4.25
31004Airport3
41005Airport4
51006Downtown7
61007Campus6
71008Riverside9
81009Airport8.5
91010Downtown14
101011Downtown3
111012Airport3.25
121013Campus3
131014Campus17
141015Airport6.5
151016Downtown4
161017Airport4
171018Campus6
181019Airport4.25
191020Airport12
201021Downtown4.25
211022Riverside8.5
221023Campus7
231024Airport4.5
241025Downtown34
251026Downtown18
261027Airport4.75
271028Campus3
281029Riverside3
291030Campus4.25

30 rows × 3 columns

Press the steps in order. This split → apply → combine pattern is the same in pandas, SQL (GROUP BY) and spreadsheets (pivot tables).

Groupby patterns

orders.groupby("branch")["total"].sum()                       # one statistic
orders.groupby(["branch", "category"])["total"].sum()         # two keys
orders.groupby("branch").agg(n_orders=("order_id", "count"),  # named aggregations
                             revenue=("total", "sum"),
                             avg_order=("total", "mean"))

Add .reset_index() to turn the group labels back into ordinary columns, and .sort_values(…) to rank.

Pivot tables and crosstabs

orders.pivot_table(index="branch", columns="category", values="total",
                   aggfunc="sum", margins=True)          # margins adds totals
pd.crosstab(orders["branch"], orders["payment"], normalize="index")   # shares per row

Percent of total and per-group calculations

share = revenue / revenue.sum(). To compare each row with its own group, use transform: orders["branch_avg"] = orders.groupby("branch")["total"].transform("mean") puts the group's average on every row.

Grouping by time

orders.groupby(orders["date"].dt.to_period("M"))["total"].sum() totals per month. With a date index, .resample("W") does weekly totals.

A branch scorecard

Exercise

Item league table

Build items: one row per item with named columns orders (count of order_id), units (sum of qty) and revenue (sum of total, rounded to 2 decimals), sorted by revenue from highest to lowest.

Code that runs before yours
import pandas as pd
orders = pd.read_csv("kc_orders.csv", parse_dates=["date"])

Exercise

Revenue by branch and daypart

A daypart column (Morning or Later) is ready. Make pt: a pivot table with branches as rows, dayparts as columns, and the sum of total as values, rounded to 0 decimals. Then set morning_leader to the branch with the most Morning revenue.

Code that runs before yours
import pandas as pd
orders = pd.read_csv("kc_orders.csv", parse_dates=["date"])
import numpy as np
orders["daypart"] = np.where(orders["hour"] < 11, "Morning", "Later")

Check your understanding0 of 3 correct

Question 1

1.groupby('branch')['total'].mean() returns…

Question 2

2.What does transform('mean') do differently from agg('mean')?

Question 3

3.pd.crosstab(a, b, normalize='index') shows…

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.