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 · WR4 · 12 MIN

Review · Reshape and connect

Task 1 · Retrieve and combine

Exercises within this concept

  1. Task 1Retrieve and combineCurrent exercise
  2. Task 2Retrieve and combine
  3. Task 3Retrieve and combine
  4. Task 4Retrieve and combine
Task 1 · Pet adoption

For df records with age at least 2, display average weight and row count by species.

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

Your requirements

  1. Use columns species, average, n, in that order.

Your inputs

Pet adoption · 6 synthetic rows
namespeciesageweightroom
MiloCat34.2A
PepperDog718.5B
LunaCat23.6A
BeanRabbit42.4B
RexDog522A
NoriRabbit11.8B

Revisit the concept lesson →

Remember the idea

Concept sketch: one row per group, multiple summariesgroupvalueA2A4B8groupmeannA32B81one row per group, multiple summaries

Rows with the same flavour form a group. .agg(...) means aggregate: it makes one result row per group by running the calculations inside. Each new_name=("input", "operation") defines one output column: the left name is its heading; the pair chooses the source field and calculation.

A small example

Fruity has prices 2 and 4, so its mean_amount is (2 + 4) / 2 = 3 and records is 2. Mint has one price, 8, so its mean_amount is 8 and records is 1.

Result after .agg(...)
flavourmean_amountrecords
fruity32
mint81
What each choice does
Code or choiceMeaning
df.groupby("flavour", as_index=False)Collect rows by flavour and keep flavour as a regular output column.
.agg(...)Aggregate: reduce each group to one result row using the named calculations inside.
mean_amount=("price", "mean")Create an output column called mean_amount from the mean of price in each group.
records=("price", "size")Create an output column called records from the row count in each group.
Hint

size counts records; count counts known measurements.

Reveal solution

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

df[df["age"] >= 2].groupby("species", as_index=False).agg(
    average=("weight", "mean"), n=("weight", "size")
)
Your task · Task 1
  1. For df records with age at least 2, display average weight and row count by species.
  2. Use columns species, average, n, in that order.

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.