pandas groupby + agg — Beginner Guide
Read this guide in: English · मराठी · हिंदी
groupby splits rows into groups, aggregates each group (sum, mean, count), and returns a compact table. Instagram-like likes: Mumbai 80+40=120, Pune 70.
Chala mitrano! Row-by-row likes hide the city story. groupby is the pivot table of pandas. Tiny numbers. Clear keys. Samajla ka?
Quick answer
Vertical groupby path:
- Start from clean row-level data (one row = one post or sale).
- Choose keys: e.g.
city. df.groupby("city")["likes"].sum()- Or named agg for several stats.
reset_index()when you need a flat table for charts.- Compare with
value_countsfor category counts.
split → apply sum/mean/count → combine
Language: English · मराठी · हिंदी
What do I need before this guide?
- Filtering basics.
- Course: Why groupby.
Before and after (look at the tables first)
Before — Instagram-like likes still row by row.
After — groupby("city").sum(); Mumbai 120, Pune 70.
Before: three posts. After: Mumbai 120, Pune 70.
Sample engagement table
| city | likes |
|---|---|
| Mumbai | 80 |
| Mumbai | 40 |
| Pune | 70 |
import pandas as pd
df = pd.DataFrame({"city": ["Mumbai", "Mumbai", "Pune"], "likes": [80, 40, 70]})
df.groupby("city")["likes"].sum()
What you see: Mumbai 120, Pune 70. What it means: likes added inside each city.
Named aggregation
(df.groupby("city")
.agg(total_likes=("likes", "sum"),
posts=("likes", "count"))
.reset_index())
Course: Multiple keys and named agg.
Shop sales groupby
Group by channel on the four-row shop file:
- Online → 190
- Store → 70
Two keys: groupby(["city", "channel"]) when you need both.
value_counts vs groupby
df["city"].value_counts()— how many rows per city.groupby— totals/means of measures like likes or sales.
Course: value_counts vs groupby.
Infosys-style hours
| client | hours |
|---|---|
| A | 40 |
| B | 20 |
| A | 30 |
groupby("client")["hours"].sum() → A 70, B 20.
Ravindra Bagale's Tip
If groupby looks random, print df.head() and say the grain: “one row = one post.” Wrong grain breaks every total. Samajla ka?
Practice task
- Recreate the three-row likes table.
- Sum likes by city; confirm Mumbai 120.
- Add named agg with post counts.
- groupby channel on the shop table; Online 190.
Samajla ka? groupby splits, aggregates, combines. Mumbai 120, Pune 70. Then chart it. Aata pudhe jaauya.
Frequently asked questions
What does groupby do?
Splits rows into groups, applies an aggregation, combines results.
Can I group by two columns?
Yes: groupby(["city", "channel"]).
Why is my result a Series?
Selecting one column then sum often returns a Series — reset_index or to_frame if you want a DataFrame.
mean vs sum?
sum for totals; mean for averages. Count for how many rows landed in the group.
Empty groups?
By default you only see groups that exist in the data.
Course links?
groupby chapter — why groupby, named agg, value_counts.