TECHNOLOGIESTieInn Technologies

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=False or .reset_index() to get them back as columns.
  • count skips NaN; size counts every row.
  • agg collapses rows; transform keeps one value per original row (handy for shares and group averages).
  • NaN keys are dropped by default; pass dropna=False to keep them.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    groupby and aggregation

  1. Question 1easy

    In df.groupby("city"), what's the difference between .size() and ["email"].count()?

  2. groupby and aggregation

  3. Question 2medium

    Customers live in 9 cities, and 3 have no city. What does this print?

    print(len(customers.groupby("city").size()))
  4. groupby and aggregation

  5. Question 3medium

    What does this print?

    print(orders.groupby("customer_id").size().max())
  6. groupby and aggregation

  7. Question 4medium

    What does this print?

    counts = orders.groupby("status").size()
    print(len(counts[counts > 10]))
  8. groupby and aggregation

  9. Question 5hard

    Store in result a DataFrame with customer_id and spend (sum of quantity * unit_price over 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

11 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.