groupby and aggregation
Python · 16 questions
Short notes
Key idea
groupby splits rows by a column, applies an aggregate to each group and combines the results: the pandas version of SQL's GROUP BY.
Syntax
df.groupby("city")["amount"].sum()
df.groupby("city")["amount"].agg(["count", "mean", "max"])
df.groupby(["city", "month"], as_index=False)["amount"].sum()
df.groupby("city").agg(orders=("order_id", "count"),
revenue=("amount", "sum"))
df["share"] = df["amount"] / df.groupby("city")["amount"].transform("sum")
Example
summary = (df.groupby("city")
.agg(orders=("order_id", "count"), revenue=("amount", "sum"))
.sort_values("revenue", ascending=False))
print(summary.head())
Named aggregation (orders=("order_id", "count")) gives clean column names in one step.
Traps
- The group keys become the index. Use
as_index=Falseor.reset_index()to get them back as columns. countskips NaN;sizecounts every row.aggcollapses rows;transformkeeps one value per original row (handy for shares and group averages).- NaN keys are dropped by default; pass
dropna=Falseto keep them.
Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →
- Question 1easy
In
df.groupby("city"), what's the difference between.size()and["email"].count()? - Question 2medium
Customers live in 9 cities, and 3 have no city. What does this print?
print(len(customers.groupby("city").size())) - Question 3medium
What does this print?
print(orders.groupby("customer_id").size().max()) - Question 4medium
What does this print?
counts = orders.groupby("status").size() print(len(counts[counts > 10])) - Question 5hard
Store in
resulta DataFrame withcustomer_idandspend(sum ofquantity * unit_priceover all their order lines), one row per customer who ordered.The tables are ready as DataFrames with the same names. Store your answer in
result.Tables
groupby and aggregation
groupby and aggregation
groupby and aggregation
groupby and aggregation
groupby and aggregation
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.