Skip to main content
Albero Academy

GroupBy

Split-apply-combine — summarise data by category.

Aggregation & Combining10 min

groupby is where pandas answers business questions: "average package per programme", "count per city". It follows the split-apply-combine pattern — split rows into groups, apply an aggregation to each, combine the results.

Grouping & aggregating

one line answers
df.groupby("programme")["package"].mean() # avg package per programme
df.groupby("programme").size() # rows per programme
df.groupby(["programme", "year"])["package"].mean() # two keys

How it works

A groupby object is lazy — nothing computes until you apply an aggregation (mean, sum, count, max…). The group keys become the index of the result:

reset_index for a flat table
result = df.groupby("programme")["package"].mean().reset_index()
# reset_index turns the group key back into a normal column

Key takeaways

  1. 01groupby follows split-apply-combine: split into groups, aggregate each, combine.
  2. 02df.groupby(key)[col].agg() answers "per-category" questions.
  3. 03Group by multiple keys with a list.
  4. 04reset_index() flattens the group keys back into columns.

Finished this chapter?

Mark it complete to track your progress through Pandas.