Section 4 · Lesson 1

Grouping and aggregating with groupby

Summarize data by category with groupby, agg and named aggregations.

35 min 3 practice tasks
When should I use a "groupby" in pandas? by Data School on YouTube

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:

  1. Split the rows into groups that share a value (all search rows, all video rows…).
  2. Apply a calculation to each group (sum, mean, count…).
  3. 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 for groupby when 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.

1

Order totals by status

Load 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?
  1. orders.groupby("status") splits the rows by status.
  2. Then pick the column to summarize and the function: ["amount"].sum().
  3. Finish with .round(2).
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

ROAS by campaign

Load 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?
  1. stats.groupby("campaign_id")[["spend", "revenue"]].sum() gives both totals per campaign.
  2. Compute roas from the summed columns, like any derived column.
  3. campaign_summary["roas"].idxmax() returns the index label (the campaign_id) of the largest value.
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Budget summary by channel

Load campaigns.csv into campaigns. Use groupby with named aggregation to build channel_summary, one row per channel (as the index), with these columns:

columnmeaning
campaignsnumber of campaigns (count of id)
total_budgetsum of daily_budget
avg_budgetmean of daily_budget, rounded to 1 decimal

Sort it by total_budget, largest first.

Need a hint?
  1. Named aggregation: .agg(new_name=("column", "function"), ...).
  2. campaigns=("id", "count") counts campaigns per channel.
  3. Round the average afterwards, then .sort_values("total_budget", ascending=False).
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country