1. Home
  2. Data Science
  3. Pandas
  4. How does df.groupby('k')['x'].transform('mean') differ…

Added 30 Nov -0001

How does df.groupby('k')['x'].transform('mean') differ from .apply('mean')?

  1. Both return one row per group, differing only in the index name that the resulting object carries afterwards
  2. transform can only be used with user-defined functions, while apply also accepts built-in method strings
  3. transform returns a Series aligned to the original index with the same length, while apply returns one value per group Correct answer
  4. apply returns a column the same length as the input frame itself, while transform reduces the result to one row per group

Correct answer

C. transform returns a Series aligned to the original index with the same length, while apply returns one value per group

13 views

MCQSEXAM

Explanation

transform versus apply: transform broadcasts a group-level result back to every row of that group, so df['x'] - df.groupby('k')['x'].transform('mean') centres values within groups. apply returns an aggregated object with one row per group unless the function returns a like-indexed object. Filtering whole groups by size uses filter, a third distinct method.

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