Sub topic 6
Stable sorts and ignore_index
This chapter assumes you can build a DataFrame, call sort_values on one or more columns, and read the index labels on the left of a printed table. Here you will control what happens to rows that tie, and what happens to the index after a sort.
What a stable sort guarantees
Rows tie when they have equal values in the sort column. A stable sort keeps tied rows in the order they had before sorting. An unstable sort may reorder them.
Ties are common. In the sales table, price has only two distinct values, so many rows tie.
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 index labels stay in increasing order (0, 3, 4, then 1, 2, 5).
The kind argument
kind selects the sorting algorithm.
| Value | Stable? | Notes |
|---|---|---|
| `"quicksort"` | No | The default. |
| `"mergesort"` | Yes | Older name for a stable sort. |
| `"stable"` | Yes | Picks a stable algorithm for you. |
| `"heapsort"` | No | Rarely needed. |
Two details cause most mistakes:
- The default is not guaranteed to keep ties in order. Your output may look stable on a small table and still not be stable on a larger one.
kindapplies only when you sort by a single column or label. When you pass a list of columns, pandas uses its own multi-column sort and ignoreskind. That multi-column sort keeps ties in their original order.
Sorting in passes
Stability lets you build a multi-key sort one key at a time. Sort by the least important key first. Then sort by the most important key with a stable sort. The second sort keeps the first sort's order inside each group.
by_units = df.sort_values("units", ascending=False)
by_region = by_units.sort_values("region", kind="stable")
print(by_region) region product units price
3 East A 8.0 2.5
5 East B 7.0 4.0
0 North A 10.0 2.5
2 North B NaN 4.0
4 South A 12.0 2.5
1 South B 5.0 4.0The result matches df.sort_values(["region", "units"], ascending=[True, False]). The passes are useful when the two keys need different treatment, such as a key function on only one of them.
Resetting the index with ignore_index
A sort moves rows but keeps their original index labels. The labels in the output above run 3, 5, 0, 2, 4, 1. That is correct, because the labels still identify the same rows. It can be unhelpful when you want to show the result or select by position.
Pass ignore_index=True to renumber the result from 0 to n-1.
print(df.sort_values("price", kind="stable", ignore_index=True)) region product units price
0 North A 10.0 2.5
1 East A 8.0 2.5
2 South A 12.0 2.5
3 South B 5.0 4.0
4 North B NaN 4.0
5 East B 7.0 4.0The call df.sort_values(...).reset_index(drop=True) gives the same result. The ignore_index argument does it in one step.
Exercise
You sort df by price with the default kind and get tied rows in a different order from the original. Which single argument makes tied rows keep their original order? Which argument gives the result a fresh 0-to-n-1 index?
Show answer
Add kind="stable" to keep tied rows in their original order, and ignore_index=True to renumber the index. For example: df.sort_values("price", kind="stable", ignore_index=True).
Exercise
You call df.sort_values(["region", "units"], kind="heapsort"). Does the kind value change the result? Why?
Show answer
No. kind only applies when sorting on a single column or label. With a list of columns, pandas uses its own multi-column sort, which keeps ties in their original order.