pandas groupby + agg — शुरुआती guide
Read this guide in: English · मराठी · हिंदी
groupby rows को groups में तोड़ता है, हर group पर aggregate करता है (sum, mean, count), और compact table देता है। Instagram-like likes: Mumbai 80+40=120, Pune 70.
दोस्तों! Row-by-row likes city कहानी छुपाते हैं। groupby = pandas का pivot table। Tiny numbers। साफ़ keys। समझा?
संक्षिप्त उत्तर
खड़ा groupby path:
- Clean row-level data (एक row = एक post या sale)।
- Key चुनो: जैसे
city। df.groupby("city")["likes"].sum()- कई stats के लिए named agg।
- Charts के लिए flat table हो तो
reset_index()। - Category counts के लिए
value_countsसे तुलना।
split → apply sum/mean/count → combine
Language: English · मराठी · हिंदी
इस guide से पहले क्या चाहिए?
- Filtering basics।
- Course: Why groupby.
Before और after
Before — Instagram-like likes still row by row.
After — groupby("city").sum(); Mumbai 120, Pune 70.
Before: तीन posts। After: Mumbai 120, Pune 70.
Sample + code
import pandas as pd
df = pd.DataFrame({"city": ["Mumbai", "Mumbai", "Pune"], "likes": [80, 40, 70]})
df.groupby("city")["likes"].sum()
Mumbai 120, Pune 70.
Named aggregation
(df.groupby("city")
.agg(total_likes=("likes", "sum"),
posts=("likes", "count"))
.reset_index())
Shop + Infosys
Shop channel groupby: Online 190, Store 70. Client hours: A 70, B 20.
value_counts vs groupby
value_counts = कितनी rows। groupby = measures के totals/means।
Ravindra Bagale's Tip
groupby अजीब लगे तो head() करके grain बोलो: “एक row = एक post।” गलत grain हर total तोड़ता है। समझा?
Practice task
- तीन-row likes।
- City sum; Mumbai 120.
- Named agg।
- Shop channel; Online 190.
Learn it properly
Related: Filter rows and columns · EDA checklist
Samajla ka? groupby = split, aggregate, combine। Mumbai 120, Pune 70. फिर chart। अब आगे चलें।
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.