sort_values
What it is
Sorts by one or more columns, with ascending accepting a list to mix directions, and na_position deciding where missing values land.
Why it matters
Sorting on several keys is how you make an order deterministic — the second key breaks ties the first one leaves.
In the real world: Sorting products by units sold, then by revenue, to build the “best sellers” page on an online store.
Visual example
SortingA second sort key breaks ties, so the order no longer depends on how the rows arrived.
Why this matters
A 'top N' that changes between runs on the same data is a bug nobody can reproduce. A tiebreak makes it deterministic.
Common misconception
Wrong idea: sorting always gives the same order.
Correct idea: tied rows keep whatever order they arrived in. Without a tiebreak, the winner depends on the input.
df.sort_values(
["customer_id", "ordered_at"],
ascending=[True, False],
na_position="last",
)Sorting by a single key and taking the head, when ties exist. The winner is then whichever row happened to be first, which changes between runs and makes the result impossible to test.
Practise it: Keep Only Each User's Latest Row, Top N Products by Revenue, The Top Three Per Group, Deterministically