Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Wrangle / Preprocess lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Groups & reshaping · W20 · 8 MIN

Groupwise transformation

Add a group statistic beside each original row.

Exercises within this concept

  1. FollowFollow the techniqueCurrent exercise
  2. ChangeAdapt a requirement
  3. TransferChoose and combine

Understand the idea

transform returns a group statistic at every original row. This lets each observation be compared with its own group.

Concept sketch: group means aligned to original rowsgroupvaluemeanA23A43B88group means aligned to original rows
Illustration · not the exercise output

A small example

For A: 2, A: 6, B: 9, transform("mean") returns 4, 4, 9; subtracting gives −2, 2, 0.

Follow the code

Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.

df["group_mean"] = df.groupby("flavour")["price"].transform("mean")
df

What each part does

df.groupby("flavour")
Make one group for each flavour.
["price"]
Select the price values to summarise inside each group.
.transform("mean")
Calculate each group mean and repeat it at every original row in that group.
df["group_mean"] =
Store those aligned means in a new column beside the original rows.

Your inputs

The editable setup on the right creates df. Run executes the setup and your work from top to bottom.

Candy shop · 6 synthetic rows
candyflavourpriceratingshelf
Gummy Bearfruity1.24.1A
Choco Popchocolate2.14.6B
Mint Bitemint1.53.8A
Berry Loopfruity2.84.4B
Cocoa Cubechocolate3.44.9A
Lemon Dropfruity1.84B

Your task · Follow

  1. Using df, add group_mean containing the mean price for each row’s flavour category.
  2. Preserve all rows.
  3. Keep the changes in df and display it.
  4. Use: transform().
Hint

transform keeps one result per original row; agg would reduce each group.

Reveal solution

One way to do it. Keep any supplied setup in the editor and use this in the Your work section.

df["group_mean"] = df.groupby("flavour")["price"].transform("mean")
df
Your task · Follow
  1. Using df, add group_mean containing the mean price for each row’s flavour category.
  2. Preserve all rows.
  3. Keep the changes in df and display it.
  4. Use: transform().

Tab: indent · Shift+Tab: outdent · Esc, then Tab: leave editor

Edit Python. Control or Command plus Enter runs it. Tab indents by four spaces. Shift plus Tab outdents. Press Escape, then Tab or Shift plus Tab to leave the editor.

Each run executes all editor code in a fresh Python session. Display a value by leaving it on the final line.

Python starts when you open a lesson.

Output

Run your code to see what Python returns.