“Total sales by city”, “average marks by batch”, “number of enquiries per course”: these summaries are the bread and butter of analysis. In pandas, they all use groupby, which works like SQL’s GROUP BY.
Split, apply, combine
df.groupby("city")["amount"].sum()
Pandas splits the rows into groups by city, applies sum to the amount column of each group, and combines the results into one Series indexed by city.
Common aggregations
.sum(),.mean(),.median(),.min(),.max().count()counts non-empty values;.size()counts rows including blanks..nunique()counts distinct values, such as unique customers per city.
Several statistics at once
summary = df.groupby("course").agg(
enquiries=("enquiry_id", "count"),
avg_age=("age", "mean"),
cities=("city", "nunique"),
).reset_index()
Named aggregation gives clear column names, and reset_index() turns the result back into a normal DataFrame ready for export or charts.
Grouping by more than one column
df.groupby(["city", "course"])["amount"].sum().unstack(fill_value=0) builds a pivot-style table with cities as rows and courses as columns. pd.pivot_table does the same in one call.
Grouping by month
Convert dates first with pd.to_datetime, then use df.groupby(df["order_date"].dt.to_period("M"))["amount"].sum() for monthly totals.
Adding group results back to rows
df["city_total"] = df.groupby("city")["amount"].transform("sum") keeps every row and adds the group total, useful for calculating each order’s share of its city.
Common mistakes
- Text numbers that will not sum: convert with
pd.to_numericfirst. - Blank group values silently dropped: use
dropna=Falseto keep them. - Forgetting
reset_index()and then struggling with a grouped index.
Related: pandas for beginners and SQL GROUP BY and HAVING.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
