Sub topic 4
Sorting by index labels
This chapter covers sort_index, which orders a DataFrame by its row labels instead of its values. It assumes you can build a DataFrame, select columns, and use sort_values from the earlier chapters.
What sort_index does
sort_values orders rows by the contents of a column. sort_index orders them by the index, which is the set of labels on the left. This is useful when the index carries meaning, such as a region name or a date.
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],
})
by_region = df.set_index("region")
print(by_region.sort_index())The rows now appear as East, East, North, North, South, South. The index has duplicate labels, and that is allowed.
Like sort_values, sort_index returns a new object and leaves the original unchanged.
Useful arguments
| Argument | Effect |
|---|---|
| `ascending=False` | Sorts labels from largest to smallest. |
| `axis=1` | Sorts the column labels instead of the row labels. |
| `level=` | Sorts a MultiIndex by one of its levels. |
| `na_position=` | Places missing labels first or last. |
| `key=` | Transforms the labels before comparing them. |
print(by_region.sort_index(ascending=False))
print(df.sort_index(axis=1))The second call orders the columns alphabetically: price, product, region, units.
Restoring the original order
A common use is undoing a value sort. The default index records each row's original position, so sorting by it brings the rows back.
shuffled = df.sort_values("units", ascending=False)
print(shuffled.sort_index())This only works while the index still holds the original positions. If you used ignore_index=True when sorting, the old labels are gone.
Sorting a MultiIndex
With several index levels, level picks the one to sort by. By default the remaining levels are sorted afterwards (sort_remaining=True).
multi = df.set_index(["region", "product"])
print(multi.sort_index(level="product"))Rows are ordered by product first, then by region within each product.
Why a sorted index matters
Label slicing with .loc needs a sorted index when labels repeat. On an unsorted index with duplicates, pandas raises a KeyError. After sorting, the slice works and includes both end labels.
ordered = by_region.sort_index()
print(ordered.loc["East":"North"])Common errors
- Expecting
sort_indexto order by values. It never looks at the data. - Forgetting to assign the result.
by_region.sort_index()on its own changes nothing. - Sorting strings with mixed case. Uppercase letters sort before lowercase, so
"Zed"comes before"apple". Fix this withkey=lambda idx: idx.str.lower(). - Mixing types in one index, such as integers and strings. Comparing them raises a
TypeError.
Exercise
You run result = df.sort_values("units").sort_index(). What order are the rows in, and why?
Show answer
They are in the original order of df. The first call reorders by units, and sort_index then orders by the default positional index, which undoes that reordering.