Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔢 Week 2 – NumPy और Pandas  ·  दिन 13

दिन 13: GroupBy, Aggregation और Pivot Tables

⏱ 2 hours📶 Intermediate🎯 100% self-study
दिन 13 / 60

✅ आज आप सीखेंगे

  • Split → apply → combine
  • sum, mean, count, nunique के साथ groupby
  • agg() से named aggregations
  • “Group का हिस्सा” के लिए transform
  • Excel जैसा pivot_table और crosstab

🏢 असली दुनिया में

हर सोमवार regional manager माँगता है “region और category के हिसाब से revenue, orders और average bill, साथ में हर शहर का अपने region में हिस्सा”। groupby और pivot_table से यह weekly report Excel में पूरी दोपहर की जगह 10 lines में बनती है।

Split → apply → combine

Key से rows बाँटें (region)हर group पर function लगाएँ (sum)Results को table में जोड़ें
groupby क्या करता है
Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
print(sales.groupby("region")["revenue"].sum().round())
print(sales.groupby("category")["rating"].mean().round(2).sort_values())
region East 1299826.0 North 1600660.0 South 2081689.0 West 1897608.0 Name: revenue, dtype: float64 category Grocery 4.04 Fashion 4.05 Home & Kitchen 4.06 Electronics 4.08 Books & Stationery 4.10 Name: rating, dtype: float64

एक साथ कई statistics

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
report = sales.groupby("region").agg(
    orders=("order_id", "count"),
    cities=("city", "nunique"),
    revenue=("revenue", "sum"),
    avg_bill=("revenue", "mean"),
    avg_rating=("rating", "mean"),
).round(1).sort_values("revenue", ascending=False)
print(report)
orders cities revenue avg_bill avg_rating region South 654 3 2081689.0 3183.0 4.1 West 519 3 1897607.7 3656.3 4.1 North 508 3 1600659.8 3150.9 4.0 East 319 2 1299826.2 4074.7 4.0
Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
two = sales.groupby(["region", "category"])["revenue"].sum().round()
print(two.head(7))
print(two.unstack().fillna(0).astype(int))          # long -> wide
region category East Books & Stationery 42697.0 Electronics 853186.0 Fashion 212273.0 Grocery 118959.0 Home & Kitchen 72711.0 North Books & Stationery 91710.0 Electronics 747832.0 Name: revenue, dtype: float64 category Books & Stationery Electronics Fashion Grocery Home & Kitchen region East 42697 853186 212273 118959 72711 North 91710 747832 467318 215108 78692 South 79562 1151046 457677 237789 155616 West 96012 1087347 377749 218082 118417

transform – हर row रखें

agg हर group की एक row देता है। transform हर original row के लिए value देता है, ताकि हर row की उसके group से तुलना हो सके।

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
city = sales.groupby(["region", "city"], as_index=False)["revenue"].sum()
city["share_of_region_%"] = (city["revenue"] / city.groupby("region")["revenue"].transform("sum") * 100).round(1)
print(city.sort_values(["region", "share_of_region_%"], ascending=[True, False]).to_string(index=False))
region city revenue share_of_region_% East Kolkata 839885.10 64.6 East Patna 459941.15 35.4 North Delhi 945592.45 59.1 North Lucknow 394912.00 24.7 North Jaipur 260155.35 16.3 South Bengaluru 964019.65 46.3 South Hyderabad 572190.15 27.5 South Chennai 545479.20 26.2 West Mumbai 1043230.20 55.0 West Ahmedabad 450611.90 23.7 West Pune 403765.60 21.3
Python
import pandas as pd
st = pd.read_csv("students_performance.csv")
st["school_avg"] = st.groupby("school_type")["maths"].transform("mean").round(1)
st["above_school_avg"] = st["maths"] > st["school_avg"]
print(st[["student_id", "school_type", "maths", "school_avg", "above_school_avg"]].head())
student_id school_type maths school_avg above_school_avg 0 S1001 Government 65.0 64.9 True 1 S1002 Private 50.0 65.0 False 2 S1003 Private 50.0 65.0 False 3 S1004 Private 68.0 65.0 True 4 S1005 Government 67.0 64.9 True

pivot_table – एक line में Excel pivot

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
sales["month"] = pd.to_datetime(sales["order_date"]).dt.month
pv = pd.pivot_table(sales, index="category", columns="region", values="revenue",
                    aggfunc="sum", margins=True, margins_name="Total").round(-2)
print((pv / 1000).round(1))            # in ₹ thousand
region East North South West Total category Books & Stationery 42.7 91.7 79.6 96.0 310.0 Electronics 853.2 747.8 1151.0 1087.3 3839.4 Fashion 212.3 467.3 457.7 377.7 1515.0 Grocery 119.0 215.1 237.8 218.1 789.9 Home & Kitchen 72.7 78.7 155.6 118.4 425.4 Total 1299.8 1600.7 2081.7 1897.6 6879.8
Python
import pandas as pd
import matplotlib.pyplot as plt
sales = pd.read_csv("sales_data.csv")
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
pv = pd.pivot_table(sales, index="category", columns="region", values="revenue", aggfunc="sum") / 100000
pv.plot(kind="bar", figsize=(9, 4.6))
plt.title("Revenue by category and region (₹ lakh)")
plt.ylabel("₹ lakh"); plt.xticks(rotation=0)
plt.show()
Category और region के हिसाब से revenue का grouped bar chart
Pivot table सीधे plot होती है – table से chart एक line में।

crosstab – counts और percentages

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv")
print(pd.crosstab(sales["region"], sales["payment_mode"]))
print((pd.crosstab(sales["region"], sales["payment_mode"], normalize="index") * 100).round(1))
payment_mode Card Cash on Delivery Net Banking UPI region East 75 60 22 162 North 122 101 42 243 South 163 127 56 308 West 125 103 43 248 payment_mode Card Cash on Delivery Net Banking UPI region East 23.5 18.8 6.9 50.8 North 24.0 19.9 8.3 47.8 South 24.9 19.4 8.6 47.1 West 24.1 19.8 8.3 47.8
💡 crosstab से insight

Region के हिसाब से Cash-on-Delivery का हिस्सा देखें। जिस region में COD ज़्यादा है वहाँ returns और cash संभालने का ख़र्च ज़्यादा – business वहाँ UPI cashback दे सकता है।

असली example: सोमवार की sales report

Python
import pandas as pd
sales = pd.read_csv("sales_data.csv", parse_dates=["order_date"])
sales["revenue"] = sales["quantity"] * sales["unit_price"] * (1 - sales["discount"])
sales["quarter"] = "Q" + sales["order_date"].dt.quarter.astype(str)
q = sales.groupby("quarter").agg(orders=("order_id", "count"), revenue=("revenue", "sum"))
q["growth_%"] = (q["revenue"].pct_change() * 100).round(1)
q["revenue"] = (q["revenue"] / 1e5).round(2)
print(q.rename(columns={"revenue": "revenue_lakh"}))
top = (sales.groupby(["quarter", "product"])["revenue"].sum().reset_index()
            .sort_values("revenue", ascending=False).groupby("quarter").head(1))
print(top.sort_values("quarter").to_string(index=False))
orders revenue_lakh growth_% quarter Q1 463 18.16 NaN Q2 406 13.41 -26.2 Q3 442 13.81 3.0 Q4 689 23.41 69.5 quarter product revenue Q1 Laptop 455852.50 Q2 Laptop 318206.05 Q3 Mobile Phone 363518.70 Q4 Mobile Phone 701427.70

🏅 आज के Job Skills

✔ groupby + agg से summary✔ transform से rows की group से तुलना✔ Excel जैसी pivot tables बनाना✔ Percentage crosstabs बनाना

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: Houses dataset से city और furnishing type के हिसाब से औसत कीमत की pivot table बनाएँ।
Solution देखें
Python
import pandas as pd
h = pd.read_csv("house_prices.csv")
print(pd.pivot_table(h, index="city", columns="furnishing", values="price_lakh", aggfunc="mean").round(1))
furnishing Furnished Semi-Furnished Unfurnished city Bengaluru 70.7 65.9 66.7 Hyderabad 61.3 57.9 51.4 Jaipur 51.4 40.5 43.7 Lucknow 41.2 39.9 35.6 Pune 64.4 63.9 62.5
Task 2: Contract type और internet service के हिसाब से churn rate (%) निकालें (telecom data)।
Solution देखें
Python
import pandas as pd
t = pd.read_csv("telecom_churn.csv")
t["churned"] = (t["churn"] == "Yes").astype(int)
print((t.pivot_table(index="contract", columns="internet_service", values="churned", aggfunc="mean") * 100).round(1))
internet_service DSL Fiber contract Monthly 37.8 58.6 One year 9.6 19.7 Two year 4.4 14.6
Task 3: हर school type के लिए 75+ average वाले students का % और 75+ vs बाकी students के औसत study hours दिखाएँ।
Solution देखें
Python
import pandas as pd
st = pd.read_csv("students_performance.csv")
st["top"] = st["average"] >= 75
print((st.groupby("school_type")["top"].mean() * 100).round(1))
print(st.groupby(["school_type", "top"])["study_hours"].mean().round(2).unstack())
school_type Government 21.1 Private 23.7 Name: top, dtype: float64 top False True school_type Government 2.48 4.28 Private 2.34 4.20

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. groupby("city")["sales"].sum() क्या लौटाता है?
हर group की एक value।
2. कौन original rows की संख्या बनाए रखता है?
transform group result को हर row पर वापस देता है।
3. pivot_table में margins=True क्या जोड़ता है?
एक “All/Total” row और column।
4. crosstab(..., normalize="index") क्या देता है?
normalize="columns" से हर column का जोड़ 1 होता।
5. unstack() क्या बदलता है?
अंदर का index level columns बन जाता है।

Interview corner

💼 Interview Corner

groupby में agg, apply और transform का फ़र्क?

agg हर group की एक row देता है (sum, mean जैसे reductions)। transform original rows के साथ aligned result देता है (जैसे हर row पर group mean)। apply सबसे flexible है – हर group पर कोई भी function – पर सबसे धीमा।

pivot_table, pivot से कैसे अलग है?

pivot सिर्फ़ reshape करता है और index/column जोड़ी दो बार आए तो fail होता है। pivot_table duplicates को aggfunc (default mean) से aggregate करता है और margins से totals जोड़ सकता है।

सारांश

  • groupby = split → apply → combine।
  • Named outputs वाला agg साफ़ report tables बनाता है।
  • transform हर row रखता है – shares और तुलना के लिए बढ़िया।
  • pivot_table और crosstab Excel pivots एक line में बनाते हैं।
➡️ आगे

Day 14: merge, join और concat से tables जोड़ें – pandas के अंदर SQL joins जैसा।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

groupby result में key index क्यों बन जाती है?
यही default है। Normal column वापस पाने के लिए as_index=False या .reset_index() लिखें।
क्या month जैसी गणना की गई value से group कर सकते हैं?
हाँ – Series से group करें: df.groupby(df["date"].dt.month) या पहले month column बनाएँ।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 14: Merge, Join और Concat आपकी प्रगति: 13 / 60 (22%) · Lesson 14 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें