1. Home
  2. Data Science
  3. Pandas
  4. Why use groupby(...).transform("mean") instead of…

Added 30 Nov -0001

Why use groupby(...).transform("mean") instead of groupby(...).agg("mean") in pandas?

  1. agg returns a Series while transform returns a scalar
  2. transform only works on datetime columns
  3. transform broadcasts group results back to every original row Correct answer
  4. transform is faster because it skips the grouping step entirely

Correct answer

C. transform broadcasts group results back to every original row

14 views

MCQSEXAM

Explanation

transform returns an object aligned to the original index, so each row receives its group's aggregate and the column can be assigned back with df["group_mean"] = df.groupby("k")["v"].transform("mean"). agg collapses each group to a single row instead, which is what you want for a summary table but not for filling gaps or computing within-group deviations. The transform trick is the standard vectorised way to normalise a value against its group without a separate merge.

Reference

Asked in: NTS, PPSC IT, Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More Pandas MCQs

Practise all Pandas MCQs

Similar MCQs