Skip to the workspace
Pebellslearn by building
pandas Series and DataFrames  ›  Lesson

Groupby and Aggregation

Groupby & Aggregation 15 mingroupby splits rows by a key, applies a summary such as sum or mean to each group, and combines the answers into one row per group.

python data analysis / Groupby and Aggregation

Explore each scene at your own pace.

01 · The rule

The rule

Groupby and Aggregation

The owner's favourite question is "how is each branch doing?" That is not one number but one number per branch. Filtering three times and summing three times would work, but groupby does the whole thing in one line, for three branches or three hundred.

The rule

Split by a key, apply a summary, combine into one row per group.

sales.groupby("branch")["copies"].sum()
# branch
# Chennai    10
# Delhi       9
# Pune        7

Read it in three moves:

  1. Split: groupby("branch") sorts the rows into piles, one per branch.
  2. Apply: ["copies"].sum() totals the copies inside each pile.
  3. Combine: the answers come back as a Series whose index is the branch names, sorted alphabetically.

Common summaries: sum, mean, count, min, max, median, and size, which counts rows per group:

sales.groupby("branch").size()      # Chennai 2, Delhi 3, Pune 3

For several summaries at once, use agg:

sales.groupby("branch").agg(
    total_copies=("copies", "sum"),
    avg_copies=("copies", "mean"),
    revenue=("revenue", "sum"),
)
branch total_copies avg_copies revenue
Chennai 10 5.00 1720
Delhi 9 3.00 3450
Pune 7 2.33 1790

Each name=("column", "summary") pair makes one output column, so the result has tidy names.

Group by two keys by passing a list: sales.groupby(["branch", "genre"])["copies"].sum() gives one row per branch-genre pair that actually occurs.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.