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
df.groupby("programme")["package"].mean() # avg package per programmedf.groupby("programme").size() # rows per programmedf.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:
result = df.groupby("programme")["package"].mean().reset_index()# reset_index turns the group key back into a normal column
Key takeaways
- 01groupby follows split-apply-combine: split into groups, aggregate each, combine.
- 02df.groupby(key)[col].agg() answers "per-category" questions.
- 03Group by multiple keys with a list.
- 04reset_index() flattens the group keys back into columns.
