Ravindra BagaleCourses & study guides Track your progress

Guides

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:

  1. Clean row-level data (एक row = एक post या sale)।
  2. Key चुनो: जैसे city।
  3. df.groupby("city")["likes"].sum()
  4. कई stats के लिए named agg।
  5. Charts के लिए flat table हो तो reset_index()।
  6. Category counts के लिए value_counts से तुलना।
split → apply sum/mean/count → combine

Language: English · मराठी · हिंदी

इस guide से पहले क्या चाहिए?

Before और after

Before groupby Three posts before aggregation.

Before — Instagram-like likes still row by row.

After groupby Likes summed by city.

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

  1. तीन-row likes।
  2. City sum; Mumbai 120.
  3. Named agg।
  4. Shop channel; Online 190.

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.