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 · W21 · 8 MIN

Build a pivot table

Summarise a measurement across two category axes.

Exercises within this concept

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

Understand the idea

pivot_table groups by two categories and summarizes a numeric value for each combination.

Concept sketch: pivot_table: aggregate repeated pairsgrpcolvalAX2AX4AY8grpXYA38pivot_table: aggregate repeated pairs
Illustration · not the exercise output

A small example

If Cat + room A has weights 2 and 6, its cell is 4 with aggfunc="mean" or 8 with aggfunc="sum".

Follow the code

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

df.pivot_table(index="flavour", columns="shelf", values="price", aggfunc="mean")

What each part does

index=
output row labels
columns=
output column labels
values=
numbers to summarise
aggfunc="mean"
average repeated combinations

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, return a pivot table of mean price, with flavour on rows and shelf on columns.
  2. Leave absent combinations missing.
  3. Use: pivot_table().
Hint

Choose the row categories, column categories, measured field and aggregation separately.

Reveal solution

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

df.pivot_table(index="flavour", columns="shelf", values="price", aggfunc="mean")
Your task · Follow
  1. Using df, return a pivot table of mean price, with flavour on rows and shelf on columns.
  2. Leave absent combinations missing.
  3. Use: pivot_table().

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.