Python · easy

Group a DataFrame by category and compute multiple aggregations at once.

Asked in Analytics Engineer interviews, in the Python round.

Short answer

df.groupby('cat').agg({'x':'sum','y':'mean'}).

How to answer it

Named aggregation gives each output column a name you chose, which is what makes the result usable downstream.

out = (
    df.groupby("category")
      .agg(
          revenue=("amount", "sum"),
          orders=("order_id", "nunique"),
          avg_amount=("amount", "mean"),
          first_seen=("order_date", "min"),
      )
      .reset_index()
)

The dict form, agg({"amount": ["sum", "mean"]}), works but yields a two-level column index that every later step has to flatten. Named aggregation avoids that. nunique on the order id rather than size is the difference between orders and line items when the frame has one row per item.

If a metric needs a custom function, pass a callable in the same tuple; if it needs several columns at once (revenue per order across a group), compute the row-level quantity first, then aggregate. groupby(...).apply on the whole group is the slow path and rarely necessary.

Related questions

Practice this for real