Back to Tutorials
Python for AI
Beginner

pandas GroupBy: Split, Apply, Combine

Step a table through split, apply and combine, see how missing values are counted, and watch a grouping reverse which of two bots looks better.

9 minInteractive: drag, click and try things as you read


How much does each city spend? Which customers order most? Which model does better on hard questions? All of these are the same operation in pandas, groupby, and it’s one of the most used lines in data work. groupby splits the rows into groups, applies a calculation to each group, and combines the results. Here you’ll step through that on a small table, see what happens to missing values, and watch a grouping reverse the answer to “which is better?”.

Split, apply, combine#

The name comes from Hadley Wickham’s description of a pattern that turns up everywhere: split the data into groups by the values in one column (the key), apply a function to each group on its own, and combine the answers into a new table. In pandas it reads almost like the sentence: df.groupby("city")["amount"].sum() means “split by city, take the amounts, add them up”.

Predict first

Leeds has 4 orders, and one of them has no amount recorded (NaN). What does df.groupby("city")["amount"].count() give for Leeds?

Try it
Twelve made-up café orders. Every result is worked out the way pandas does it, checked against pandas itself. Change the key or the function at any step and the rows move to their new groups.

Step through once and the pattern sticks. Split only sorts rows into groups; nothing is calculated. Apply runs the function on each group as if it were its own little table. Combine stitches the answers together, sorted by key (pandas sorts group names unless you pass sort=False).

The last control is the choice people miss. .sum(), or .agg("sum"), gives one row per group. .transform("sum") gives one value per original row: each order gets its city’s total next to it, so the table keeps all 12 rows and you can divide one by the other. agg shrinks the table to one row per group; transform keeps every row and adds the group’s answer to each.

Why it matters for machine learning#

Most useful features for tabular models are group summaries: a customer’s average order, how many times they ordered in the last 30 days, how this order compares with their usual. Each is one groupby. With several keys, df.groupby(["customer", "item"]), you get a summary for every combination; with named aggregation you get several summaries in one go (see the code below).

One warning carries over from splitting data. A feature like “this customer’s average order” uses other rows, so work it out from the training rows only, and never from rows that come after the moment you’re predicting. Otherwise the feature quietly includes the answer.

When the grouping reverses the answer#

Two support bots answered 1,000 questions each. Bot A runs on the website, where most questions are easy; bot B runs on the phone line, which gets the hard ones. Which bot is better?

Predict first

Bot B answers more easy questions correctly than bot A, in percentage terms, and more hard questions too. Can bot A still have the higher score overall?

Try it
Made-up results: bot A gets 90% of easy and 50% of hard questions right, bot B 95% and 60%. Only the mix of questions changes as you slide.

At the start, 70% of B’s questions are hard, and grouped by bot alone A wins, 82.0% to 70.5%. Group by bot and difficulty and B wins both rows. Neither table is wrong: they answer different questions. “Which bot gave more correct answers?” is A. “Which bot is better at answering?” is B, because the fair comparison is on the same kind of question. Slide B’s share of hard questions below 37% and the overall winner flips back.

This reversal is called Simpson’s paradox, and it turns up in real data. A well-known case is a 1986 study of kidney-stone treatments: open surgery succeeded more often than the newer keyhole method for small stones (93% against 87%) and for large stones (73% against 69%), yet less often overall (78% against 83%), because surgery was mostly used on the harder, large stones. Before comparing averages, check whether the groups being compared had the same mix. A groupby on the thing that might differ, like difficulty, size or region, is how you check.

In code#

The figure’s table, with several summaries at once and a feature made with transform:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    "customer": ["Amira", "Ben", "Amira", "Chloe", "Dev", "Ben", "Ella", "Chloe", "Amira", "Dev", "Ella", "Femi"],
    "city": ["London", "Leeds", "London", "Manchester", "Leeds", "Leeds", "London", "Manchester", "London", "Leeds", "London", "Manchester"],
    "item": ["Coffee", "Cake", "Sandwich", "Coffee", "Coffee", "Coffee", "Cake", "Sandwich", "Coffee", "Sandwich", "Coffee", "Cake"],
    "amount": [3.20, 4.50, 6.80, 2.90, 3.10, 3.10, 4.20, 7.10, 3.20, np.nan, 3.40, 4.80],
})

# one row per city, several results at once (named aggregation)
print(df.groupby("city").agg(total=("amount", "sum"), orders=("amount", "size"), average=("amount", "mean")).round(2))
#             total  orders  average
# city
# Leeds        10.7       4     3.57
# London       20.8       5     4.16
# Manchester   14.8       3     4.93

# one value per row: each order's share of its city's total, a ready-made feature
df["share_of_city"] = df["amount"] / df.groupby("city")["amount"].transform("sum")
print(df[["customer", "city", "amount", "share_of_city"]].head(3).round(2))
#   customer    city  amount  share_of_city
# 0    Amira  London     3.2           0.15
# 1      Ben   Leeds     4.5           0.42
# 2    Amira  London     6.8           0.33

What to remember

  • groupby splits rows by a key, applies a function to each group, and combines the answers; agg gives one row per group, transform one value per row.
  • Missing values are skipped (count skips them, size doesn’t), and rows with a missing key are dropped from the groups by default.
  • An overall average can reverse when you group by something the groups differ on (Simpson’s paradox): compare like with like.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.