Section 4 · Lesson 1
Grouping and aggregating with groupby
Summarize data by category with groupby, agg and named aggregations.
Most business questions are really “per something” questions: revenue per channel,
orders per status, ROAS per campaign. In the dictionaries lesson you wrote a loop to
total values by category. pandas does the same job with groupby, in one line.
Split, apply, combine
groupby works in three steps:
- Split the rows into groups that share a value (all
searchrows, allvideorows…). - Apply a calculation to each group (sum, mean, count…).
- Combine the results into a new, smaller table with one row per group.
import pandas as pd
orders = pd.read_csv("orders.csv")
orders.groupby("status")["amount"].sum()
# status
# cancelled 3879.22
# completed 58524.89
# refunded 5352.55
Read it left to right: group the orders by status, take the amount column, add it up. The group values become the index of the result.
Common aggregation functions
| Function | Gives you |
|---|---|
sum() |
total |
mean() / median() |
average / middle value |
count() |
number of non-missing values |
size() |
number of rows (including missing values) |
min() / max() |
smallest / largest |
nunique() |
number of distinct values |
Several columns at once
Select a list of columns to summarize them all with the same function:
stats = pd.read_csv("daily_stats.csv")
stats.groupby("campaign_id")[["impressions", "clicks", "spend"]].sum()
Different functions per column: named aggregation
When each output column needs its own calculation, use .agg() with
new_column=("source_column", "function") pairs:
summary = orders.groupby("status").agg(
orders=("id", "count"),
revenue=("amount", "sum"),
avg_order=("amount", "mean"),
)
You choose the output names, so the result is ready to share without renaming.
Ratios come after the aggregation
Remember the tip from the derived-columns lesson: to get a group’s CTR or ROAS, sum the parts first, then divide.
by_campaign = stats.groupby("campaign_id")[["spend", "revenue"]].sum()
by_campaign["roas"] = by_campaign["revenue"] / by_campaign["spend"]
Averaging a daily roas column instead would give every day equal weight, no matter how
much was spent that day.
Working with the result
The result of a groupby is an ordinary Series or DataFrame, so everything you already
know still works:
by_campaign.sort_values("roas", ascending=False).head(5) # top 5 campaigns
by_campaign["roas"].idxmax() # campaign_id with the best ROAS
by_campaign.loc[118] # one campaign's row
If you’d rather have the group column back as a regular column (handy before a merge or
an export), add .reset_index(), or pass as_index=False to groupby.
Grouping by more than one column
Pass a list to get one row per combination:
campaigns = pd.read_csv("campaigns.csv")
campaigns.groupby(["channel", "status"])["id"].count()
Tip:
df["col"].value_counts()is a shortcut for “group by this column and count rows”, sorted from most to least common. Reach forgroupbywhen you need anything other than a count.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Order totals by status
DoneLoad orders.csv into orders. Create amount_by_status: a Series with the **total amount** for each status (completed, refunded, cancelled), rounded to 2 decimals. The statuses should be the index.
Need a hint?
orders.groupby("status")splits the rows by status.- Then pick the column to summarize and the function:
["amount"].sum(). - Finish with
.round(2).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
orders = pd.read_csv("orders.csv")
amount_by_status = orders["amount"]
print(amount_by_status)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)ROAS by campaign
DoneLoad daily_stats.csv into stats.
1. Create campaign_summary: one row per campaign_id (as the index, which is what groupby gives you), with columns spend and revenue holding each campaign's totals. 2. Add a column roas to campaign_summary: total revenue ÷ total spend, rounded to 2 decimals. 3. Set best_campaign to the campaign_id (an integer) with the highest ROAS.
Need a hint?
stats.groupby("campaign_id")[["spend", "revenue"]].sum()gives both totals per campaign.- Compute
roasfrom the summed columns, like any derived column. campaign_summary["roas"].idxmax()returns the index label (the campaign_id) of the largest value.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
stats = pd.read_csv("daily_stats.csv")
campaign_summary = stats
best_campaign = None
print(campaign_summary.head())
print(best_campaign)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Budget summary by channel
DoneLoad campaigns.csv into campaigns. Use groupby with named aggregation to build channel_summary, one row per channel (as the index), with these columns:
| column | meaning |
|---|---|
campaigns | number of campaigns (count of id) |
total_budget | sum of daily_budget |
avg_budget | mean of daily_budget, rounded to 1 decimal |
Sort it by total_budget, largest first.
Need a hint?
- Named aggregation:
.agg(new_name=("column", "function"), ...). campaigns=("id", "count")counts campaigns per channel.- Round the average afterwards, then
.sort_values("total_budget", ascending=False).
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
import pandas as pd
campaigns = pd.read_csv("campaigns.csv")
channel_summary = campaigns.groupby("channel").size()
print(channel_summary)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)