pandas groupby exercises, with solutions
groupby is the method analysts use most and get wrong most. These nine exercises go from one total per group to transform and filter. Each has a worked solution here and a live version where you write the code yourself and it is checked on two datasets.
One number per group
The examples use two small tables: orders (order_id, customer, date, amount, status) with 8 rows, one of them cancelled, and customers (customer, country, segment) with 5 rows, one of whom never ordered.
1. Total amount per customer
Name the grouping column, pick the value column, choose the function. The result is a Series indexed by customer.
orders.groupby("customer")["amount"].sum()Result:
customer
acme 260.0
birch 450.0
cobalt 545.0
dune 210.0Write it yourself: Total by group, checked on two datasets.
2. The same as a flat table
as_index=False (or reset_index) keeps customer as an ordinary column, which is what you want before a merge or an export.
orders.groupby("customer", as_index=False)["amount"].mean()Result:
customer amount
0 acme 86.666667
1 birch 225.000000
2 cobalt 272.500000
3 dune 210.000000Write it yourself: Group means as a flat table, checked on two datasets.
3. Count the orders per customer
size counts rows per group. count counts the non-missing values of a column, which is not always the same thing.
orders.groupby("customer").size().reset_index(name="orders")Result:
customer orders
0 acme 3
1 birch 2
2 cobalt 2
3 dune 1Write it yourself: Count rows per group, checked on two datasets.
Try it yourself
Return the total revenue for each region as a Series indexed by region.
sales: 12 rows, first 4 shown
| order_id | region | rep | product | units | revenue | quarter |
|---|---|---|---|---|---|---|
| 1001 | "East" | "Ava" | "Widget" | 5 | 250 | "Q1" |
| 1002 | "West" | "Zed" | "Gadget" | 3 | 180 | "Q1" |
| 1003 | "East" | "Ava" | "Gizmo" | 8 | 320 | "Q1" |
| 1004 | "North" | "Moe" | "Widget" | 2 | 100 | "Q1" |
Free, no account needed. Real pandas runs in your browser; the first run takes a few seconds to load Python.
Several numbers per group
4. Named aggregations
agg with name=(column, function) pairs gives each output column a clear name and avoids a two-level header.
orders.groupby("customer", as_index=False).agg(orders=("order_id", "count"), total=("amount", "sum"), largest=("amount", "max"))Result:
customer orders total largest
0 acme 3 260.0 120.0
1 birch 2 450.0 300.0
2 cobalt 2 545.0 500.0
3 dune 1 210.0 210.0Write it yourself: Named aggregations, checked on two datasets.
5. Group by two keys
Pass a list of columns. Each distinct pair becomes a group.
orders.groupby(["customer", "status"], as_index=False)["amount"].sum()Result:
customer status amount
0 acme completed 260.0
1 birch completed 450.0
2 cobalt cancelled 45.0
3 cobalt completed 500.0
4 dune completed 210.0Write it yourself: Group by two keys, checked on two datasets.
6. Distinct values per group
nunique counts different values, here the number of months in which each customer ordered.
orders.assign(month=orders["date"].dt.strftime("%Y-%m")).groupby("customer")["month"].nunique()Result:
customer
acme 2
birch 2
cobalt 2
dune 1Write it yourself: Distinct values per group with nunique, checked on two datasets.
Back to the original rows
agg shrinks the table to one row per group. transform and filter keep the original rows, which is what most real questions need.
7. Each order as a share of its customer's total
transform returns one value per original row, so the group total lines up with every order.
orders.assign(share=(orders["amount"] / orders.groupby("customer")["amount"].transform("sum")).round(3))[["customer", "amount", "share"]]Result:
customer amount share
0 acme 120.0 0.462
1 birch 300.0 0.667
2 acme 80.0 0.308
3 cobalt 45.0 0.083
4 dune 210.0 1.000
5 birch 150.0 0.333
6 acme 60.0 0.231
7 cobalt 500.0 0.917Write it yourself: Share of the group total with transform, checked on two datasets.
8. Keep only the groups above a threshold
Aggregate, then filter the aggregate. This is SQL's HAVING.
t = orders.groupby("customer", as_index=False)["amount"].sum()
t[t["amount"] > 250]Result:
customer amount
0 acme 260.0
1 birch 450.0
2 cobalt 545.0Write it yourself: Keep the groups above a threshold, checked on two datasets.
9. Keep the rows that belong to large groups
filter keeps or drops whole groups but returns the original rows, here every order from customers with three or more orders.
orders.groupby("customer").filter(lambda g: len(g) >= 3)[["order_id", "customer", "amount"]]Result:
order_id customer amount
0 1 acme 120.0
2 3 acme 80.0
6 7 acme 60.0Write it yourself: Rows from large groups with filter, checked on two datasets.
Practice these live
Each exercise runs real pandas in your browser and checks your result on the sample and on a second dataset. Your first 8 are free, with no account.
- Group means as a flat table
- Named aggregations
- Group by two keys
- Share of the group total with transform
- Keep the groups above a threshold
- Rows from large groups with filter