Sub topic 6
Stable Sorts and ignore_index
This chapter covers two details of sort_values that affect results: what happens to rows that tie, and what happens to the index after a sort. It assumes you can build a DataFrame, select columns, and use sort_values with one or several columns and with ascending.
What a stable sort guarantees
A sort is stable if rows with equal sort keys keep the relative order they had before the sort. If row 3 came before row 4 and both have the same price, a stable sort by price leaves row 3 ahead of row 4.
Stability matters in two cases:
- Ties are common, as with prices, regions or grades. An unstable sort may order tied rows differently from run to run or between pandas and NumPy versions.
- You want to build a multi-level ordering from several passes. This only works if each later pass preserves the order produced by the earlier ones.
The sample data has ties in price.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
print(df.sort_values("price", kind="stable")) region product units price
0 North A 10.0 2.5
3 East A 8.0 2.5
4 South A 12.0 2.5
1 South B 5.0 4.0
2 North B NaN 4.0
5 East B 7.0 4.0Within each price, the original order (0, 3, 4 and then 1, 2, 5) is preserved.
The kind argument
sort_values accepts a kind argument that selects the underlying NumPy algorithm.
| `kind` | Stable? | Notes |
|---|---|---|
| `"quicksort"` | No | The default. Fast, but ties may be reordered. |
| `"mergesort"` | Yes | Guaranteed stable. |
| `"stable"` | Yes | Lets NumPy pick a stable algorithm for the dtype, so it can be faster than `"mergesort"`. |
| `"heapsort"` | No | Rarely a good choice. |
Three details help you avoid wrong assumptions:
- The default is not guaranteed stable. NumPy's quicksort uses insertion sort on very small arrays, and insertion sort is stable. A six-row test frame can therefore look stable even though the same call on a million rows may not be. Don't treat a small test as proof.
kindonly applies to a single column. When you sort by a list of columns, pandas uses a different multi-key routine and ignoreskind. That routine keeps ties in their original order.kind="stable"is the safe choice whenever the order of ties matters, such as reports, tests or reproducible exports.
sort_index also accepts kind. It has the same options, and it is ignored for a MultiIndex.
Ties and descending order
With ascending=False and a stable kind, tied rows still keep their original relative order. Pandas does not sort ascending and then reverse the result, because that would flip the ties.
print(df.sort_values("price", ascending=False, kind="stable"))The rows with price 4.0 come first, in the order 1, 2, 5. The rows with price 2.5 follow, in the order 0, 3, 4. If you want ties resolved some other way, such as by units, add the tie-breaker as a second sort column instead of relying on the original order.
Building a multi-level sort in passes
Because a stable sort preserves earlier order, sorting by the least important key first and the most important key last gives the same result as one multi-column sort. This is a common idiom, and it is useful when different columns need different treatment, such as different key functions or different na_position settings.
one_pass = df.sort_values(["region", "units"], ascending=[True, False])
two_pass = (
df.sort_values("units", ascending=False)
.sort_values("region", kind="stable")
)
print(one_pass.equals(two_pass))This prints True. The first call orders rows by units, largest first, with the missing value last. The second call orders by region, and because it is stable, rows within each region stay in units order.
The order of the passes is the part people get wrong. If you sort by region first and units second, the final order is by units, and the region order survives only among tied units.
What happens to the index
sort_values moves entire rows, and each row keeps its index label. After a sort the index is no longer 0, 1, 2 and so on. You see something like 4, 0, 3, 5, 1, 2.
That is usually what you want, because the labels still identify the original rows. It can also cause problems:
.loc[0]selects the row labelled 0, which may no longer be the first row..iloc[0]selects the first row by position.- Assigning a Series to a column aligns on index labels, not position. The assignment below shows how this goes wrong silently.
ordered = df.sort_values("units", ascending=False)
ordered["position"] = pd.Series(range(len(ordered)))
print(ordered[["units", "position"]])The author's intent is that the largest-units row gets position 0. Instead, pandas matches labels. The row labelled 4 (units 12) receives position 4, and the row labelled 0 receives position 0. No error is raised and the numbers look plausible. A plain list or array would be assigned by position, so this problem only appears with Series.
Renumbering with ignore_index
Pass ignore_index=True to discard the old labels and number the result 0 to n-1 in the new order.
ordered = df.sort_values("units", ascending=False, ignore_index=True)
ordered["position"] = pd.Series(range(len(ordered)))
print(ordered[["region", "units", "position"]])Now label and position coincide, so the alignment gives the intended answer. The call is equivalent to sorting and then calling reset_index(drop=True), in one step and without a temporary frame.
Things to keep in mind:
- The old labels are lost. If you still need them, for example to join back to the original frame, use
reset_index()withoutdrop=True. That keeps them in a newindexcolumn, or in a column with the index's name if it has one. ignore_indexonly affects the result's index. It does not change the order of the rows.- It is not the same as
inplace. The call still returns a new DataFrame unless you passinplace=True. ignore_indexis available on several other methods, includingsort_index,drop_duplicatesandpd.concat. The meaning is the same: throw away the labels and renumber.
When to use it:
| Situation | Choice |
|---|---|
| Labels identify rows you will look up or join later | Keep the labels (default) |
| The result is a final report, an export, or a display table | `ignore_index=True` |
| You will assign Series built by position or from a fresh `range` | `ignore_index=True` |
| You need both the old labels and a clean 0-to-n index | `reset_index()` |
Checking your understanding of ties
nlargest and nsmallest, which come up later in this tutorial, have their own tie rule through a keep argument. The default keep="first" favours the rows that appear first in the original order, which is the same idea as a stable sort. The shared principle is that if the order of tied rows matters to you, either state it (with kind="stable" or a tie-breaker column) or sort by enough columns that no ties remain.
Exercise
You run df.sort_values("price", kind="quicksort") on a frame with three million rows and many tied prices. A colleague says rows with equal prices will keep their original order. Is that safe to rely on, and what is the one-argument change that makes it guaranteed?
Show answer
It is not safe. Quicksort is not stable, so tied rows can come out in any order, even though a small test frame may appear stable. Pass kind="stable" (or "mergesort") so that ties keep their original relative order.
Exercise
After s = df.sort_values("units", ascending=False), you run s["rank_pos"] = pd.Series(range(len(s))). The values in rank_pos do not follow the sorted order. Why, and how do you fix it by changing only the sort call?
Show answer
Assigning a Series aligns on index labels, and s still carries its original labels in shuffled order, so each position lands on the row with the matching label. Add ignore_index=True to the sort so the labels become 0 to n-1 in sorted order and the labels agree with the positions.