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
| name | species | age | weight | room |
|---|---|---|---|---|
| Milo | Cat | 3 | 4.2 | A |
| Pepper | Dog | 7 | 18.5 | B |
| Luna | Cat | 2 | 3.6 | A |
| Bean | Rabbit | 4 | 2.4 | B |
| Rex | Dog | 5 | 22 | A |
| Nori | Rabbit | 1 | 1.8 | B |
Remember the idea
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.
| Code or choice | Meaning |
|---|---|
sort_values("score") | Smallest to largest by default (ascending=True). |
ascending=False | Largest 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])