Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations

← Inspect lessons
Reading the whole table · Lesson 24 · 9 MIN

Order a summary and extract its labels

Use a grouped Series to choose a meaningful category order.

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

Understand the idea

A grouped Series holds categories in its index and their means in its values.

Illustrative data

Click the highlighted code to change the result.

means = df.groupby()["reading"].mean()
list(means.index)
Source df
rowbenchstationreading
0ANorth2
1ASouth4
2BNorth8
3CSouth6
→
Computed means Series
benchreading
A3
B8
C6
Result["A", "B", "C"]

Grouping creates one mean per label. means.index returns those group labels, rather than the mean measurements.

Follow the code

medians = df.groupby("bench")["reading"].median()
ranked = medians.sort_values()
order = ranked.index
list(order)

What the syntax does

means = df.groupby("bench")["reading"].mean()
Calculate one mean per bench; bench names become the Series index.
list(means.index)
Return those bench labels in their existing order.
Bench summary checks
benchreading
Ash9
Cedar6
Birch2
Ash10
Cedar8
Birch4
Birch60
Ash11
Your task · Follow

Which category labels belong to the grouped means?

  1. Group all df rows by bench and calculate mean reading.
  2. Display the grouped category labels as a list in default label order.
  3. Use the grouped Series index.

Setup is included in the editor.

Hint

Group names become the summary index; the means are different values.

Reveal solution

Keep the supplied setup and replace the Your work section with this example.

means = df.groupby("bench")["reading"].mean()
list(means.index)

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.