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_id | branch | total |
|---|---|---|---|
| 0 | 1001 | Riverside | 3.5 |
| 1 | 1002 | Downtown | 12 |
| 2 | 1003 | Riverside | 4.25 |
| 3 | 1004 | Airport | 3 |
| 4 | 1005 | Airport | 4 |
| 5 | 1006 | Downtown | 7 |
| 6 | 1007 | Campus | 6 |
| 7 | 1008 | Riverside | 9 |
| 8 | 1009 | Airport | 8.5 |
| 9 | 1010 | Downtown | 14 |
| 10 | 1011 | Downtown | 3 |
| 11 | 1012 | Airport | 3.25 |
| 12 | 1013 | Campus | 3 |
| 13 | 1014 | Campus | 17 |
| 14 | 1015 | Airport | 6.5 |
| 15 | 1016 | Downtown | 4 |
| 16 | 1017 | Airport | 4 |
| 17 | 1018 | Campus | 6 |
| 18 | 1019 | Airport | 4.25 |
| 19 | 1020 | Airport | 12 |
| 20 | 1021 | Downtown | 4.25 |
| 21 | 1022 | Riverside | 8.5 |
| 22 | 1023 | Campus | 7 |
| 23 | 1024 | Airport | 4.5 |
| 24 | 1025 | Downtown | 34 |
| 25 | 1026 | Downtown | 18 |
| 26 | 1027 | Airport | 4.75 |
| 27 | 1028 | Campus | 3 |
| 28 | 1029 | Riverside | 3 |
| 29 | 1030 | Campus | 4.25 |
30 rows × 3 columns
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
Quiz score: 0 of 3
Exercises solved: 0 of 2
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.