Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Data Foundations · A little practice goes a long way.

← Inspect lessonsTINY TABLES · REAL PYTHON · YOUR PACE
Understanding values · IR3 · 12 MIN

Review · Find the surprises

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

Return df sorted first by species alphabetically, then by age from oldest to youngest within each species.

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

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: group alphabetically, then age descendingtypeageDog3Cat2Cat5typeageCat5Cat2Dog3group alphabetically, then age descending

Sorting moves whole rows together. With multiple sort keys, the first sets the main order and the next resolves ties.

A small example

Sorting group ascending, score descending puts group A before B, then higher scores first within each group.

What each choice does
Code or choiceMeaning
sort_values("score")Smallest to largest by default (ascending=True).
ascending=FalseLargest to smallest.
sort_values(["group", "score"], ascending=[True, False])Pair each column with its own direction.
Hint

Pass a list of columns and a matching list of ascending flags.

Reveal solution

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

df.sort_values(["species", "age"], ascending=[True, False])
Your task · Task 1

Return df sorted first by species alphabetically, then by age from oldest to youngest within each species.

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.