Why would you pass kind='stable' to pandas sort_values, and when does the default algorithm reorder tied rows?
answer
- what happens to equal keys
- quicksort makes no tie promise
- two passes need the second stable
- kind needs a single key
- small demos hide it
basics
~10 skind='stable' guarantees that rows with equal sort keys keep their input order. The default 'quicksort' gives no such promise, so ties can come out shuffled, which breaks multi-pass sorts and order-based tie-breaking.
solid answer
~40 s`sort_values` accepts `kind` in `'quicksort'` (default), `'mergesort'`, `'heapsort'` and `'stable'`, and only `'stable'` and `'mergesort'` are stable: rows with equal keys keep their relative input order. With the default, tied rows may come out in any order. That matters when the input order means something — a frame already sorted by sign-up date where the earlier entrant should win a revenue tie — and in **two-pass** sorts, where the second pass must be stable to keep the first pass's order within ties. `kind` applies only when `by` names a single column; with several keys pandas ignores it and sorts all keys in one pass, which is usually the cleaner fix: name the tie-breaker as a second key. A descending stable sort still keeps ties in input order.
code
python · 16 linesimport numpy as np
import pandas as pd
rng = np.random.default_rng(0)
n = 2000
sales = pd.DataFrame({
"signup": np.arange(n),
"revenue": rng.integers(1, 6, n) * 100,
})
expected = sales.sort_values(["revenue", "signup"], ascending=[False, True])
default = sales.sort_values("revenue", ascending=False)
stable = sales.sort_values("revenue", ascending=False, kind="stable")
print(default.index.equals(expected.index))
print(stable.index.equals(expected.index))go deeper
Know that stable means equal keys keep their input order, and that the default quicksort is not stable.
Explain the two-pass sort and why the second call must be stable, and that kind applies only when by names one column.
Show the production judgment: prefer an explicit tie-breaking key over hidden stability, keep descending ties correct without slicing, and test with realistic numbers of ties.
Treat tie order as part of a report's contract: require explicit tie-breakers in shared code so rankings do not change between runs or library upgrades.
## What "stable" means here A sort is **stable** when rows whose sort keys are equal come out in the same relative order they went in. `DataFrame.sort_values` and `Series.sort_values` choose the algorithm with `kind`: | `kind` | stable? | note | |---|---|---| | `'quicksort'` | no | the default | | `'heapsort'` | no | rarely chosen | | `'mergesort'` | yes | named after the algorithm | | `'stable'` | yes | says what you need, not which algorithm | pandas hands a single-key sort of a NumPy-backed column to NumPy's sort with this `kind`, and its docstring states that `mergesort` and `stable` are the only stable choices. With the default, tied rows come out in whatever order the algorithm leaves them, which is **not** guaranteed to be the input order. ## When tie order matters 1. **Order as a tie-breaker.** A leaderboard frame is already in sign-up order and the rule is "on equal revenue, the earlier sign-up ranks higher". `sales.sort_values("revenue", ascending=False, kind="stable")` honours that; the default may not. 2. **Two-pass sorts.** Sorting first by date and then by revenue only keeps the date order within equal revenues if the **second** call is stable. The first call's algorithm does not matter; the last one decides. 3. **Reproducible output.** Reports diffed day to day, snapshot tests and exported rankings should not reshuffle tied rows between runs or versions. A descending stable sort keeps ties in input order too. pandas does not produce `ascending=False` by reversing an ascending result — that would flip every group of ties. Reversing a stable ascending sort with `[::-1]` does flip them, which is a classic way to lose the order you wanted. ## Several keys: `kind` is ignored The `kind` docstring adds a limit that surprises people: for a DataFrame, it is **only applied when sorting on a single column or label**. With `by=["revenue", "signup_date"]`, pandas builds one lexicographic order over all keys in a single pass and `kind` plays no part. That points to the better design. Rather than relying on stability to carry a hidden earlier order, name the tie-breaker explicitly: ```python sales.sort_values(["revenue", "signup_date"], ascending=[False, True]) ``` The order is then visible in the call, survives anyone re-sorting the input, and does not depend on `kind` at all. Rows that tie on **every** key still come out in input order in current pandas, which goes through NumPy's lexicographic sort, but the explicit key is the part to rely on. ## A worked two-pass example Suppose a report must list rows by revenue, highest first, and within each revenue by sign-up, earliest first. Two equivalent ways to write it: ```python # two passes: the second must be stable step1 = sales.sort_values("signup") board = step1.sort_values("revenue", ascending=False, kind="stable") # one pass: the tie-breaker is named board = sales.sort_values(["revenue", "signup"], ascending=[False, True]) ``` Both give the same order. The first silently depends on two things: the earlier pass, and the `kind` of the later one; drop `kind="stable"` and ties reshuffle on large inputs. The second states the whole rule in one line, which is why reviewers prefer it. ## Why a quick test can lie On a tiny frame — a handful of rows — the default `'quicksort'` often happens to leave ties in input order, because NumPy's default sort behaves differently on very small inputs. A six-row notebook demo of an unstable sort therefore proves nothing; the reshuffling shows up on realistic sizes, such as a few thousand rows with many repeated revenue values. Test tie behaviour with data that has many ties, or simply pass `kind="stable"` whenever the order of ties is part of the requirement. ## Where else stability shows up - `DataFrame.nlargest` and `nsmallest` decide ties with their own `keep` argument rather than `kind`. - Dropping repeats after a sort ("keep the latest row per contact") depends on the sort placing the right row first or last — another reason to make the order explicit. - Ranking within groups uses a separate groupby method and is a different question. ## What to say in an interview State the guarantee (equal keys keep input order), name the two stable choices, give the two-pass example, and add the single-key limit on `kind`. The strongest finish is the design point: an explicit tie-breaking key beats an implicit dependence on stability.
- Why does df.sort_values('revenue', kind='stable')[::-1] not give a stable descending sort?Reversing the whole result reverses every group of ties as well, so the later input row now comes first. `sort_values(ascending=False, kind='stable')` is built so that ties keep their input order even in descending order. Use the argument, not a slice.
- Does kind='stable' have any effect with by=['revenue', 'units']?No. The `kind` docstring says it applies only when sorting on a single column or label. With several keys pandas sorts all of them in one lexicographic pass. If ties need a defined order, add the tie-breaker column to `by`.
- A colleague's six-row test shows quicksort keeping ties in order. Is the code safe?No. On very small inputs NumPy's default sort often happens to keep ties in order, so the test cannot expose the problem. Test with thousands of rows and many repeated keys, or pass `kind='stable'` wherever tie order is a requirement.
- sort_values is stable by default, so ties always keep their order
- kind='stable' controls tie order even when by lists several columns
- Reversing a stable ascending sort gives a stable descending sort
- The first of two sort_values calls must be the stable one
- A six-row test proves the default sort keeps ties in order