GroupBy: split - apply - combine#
groupby splits the rows into groups, applies a calculation to each, and combines the results - the pandas version of SQL GROUP BY and Excel pivot tables.
groupby का मतलब है: "बाँटो → हिसाब करो → जोड़ो" (split → apply → combine)।
df.groupby("region")["sales"].sum() = data को region के हिसाब से समूहों में बाँटो, हर समूह की sales जोड़ो, और नतीजा एक table में दिखाओ। यह SQL के GROUP BY और Excel की pivot table जैसा ही है।
Named aggregations with agg#
Several statistics at once, with clear names:
as_index=False and reset_index#
groupby puts the group keys in the index. Use as_index=False or .reset_index() to get a normal table (handy for merging and charts).
transform - group values on every row#
Ranking within groups#
df["rank_in_category"] = df.groupby("category")["sales"].rank(ascending=False, method="dense")
top3 = df.sort_values("sales", ascending=False).groupby("category").head(3)
Pivot tables#
aggfunc can be "sum", "mean", "count", "median", or a list like ["sum", "mean"].
crosstab - counts of two categories#
melt - wide to long (the opposite of pivot)#
wide = pt.reset_index()[["region", 2024, 2025]]
long = wide.melt(id_vars="region", var_name="year", value_name="sales") # like Power Query Unpivot
Merging (joins)#
pd.merge(left, right, on="key", how="left") # or left.merge(right, ...)
how= |
Like | Keeps |
|---|---|---|
"inner" (default) |
INNER JOIN | matching keys only |
"left" |
LEFT JOIN / XLOOKUP | all rows of left |
"right" |
RIGHT JOIN | all rows of right |
"outer" |
FULL OUTER JOIN | everything |
validate="many_to_one" makes pandas raise an error if the right table has duplicate keys - preventing the silent row-multiplication problem you learned about in SQL joins. Use indicator=True to see which rows matched (_merge column).
Other options: left_on="prod_name", right_on="product" when key names differ; suffixes=("_sale", "_master") when both tables have same-named columns.
Concatenating (stacking)#
Combine many monthly files:
import glob
files = glob.glob("data/sales_*.csv")
all_sales = pd.concat((pd.read_csv(f) for f in files), ignore_index=True)
Time-based grouping#
Summary#
groupby(...).agg(name=(col, func))creates clear summaries;transformreturns group values per row.pivot_table= Excel pivots;crosstab= counts/shares of two categories;melt= unpivot.merge(how=...)joins tables (usevalidateto avoid duplicates);concatstacks rows.resamplegroups by time periods;pct_changecomputes growth.