Sub topic 4
Sorting by index labels
This chapter covers sort_index, which orders a DataFrame or Series by its row labels (or column labels) instead of by its values. It assumes you can create a DataFrame, select columns, and tell a Series from a DataFrame. It also assumes you know sort_values from the earlier chapters, because sort_index shares most of its arguments.
What sort_index does
Every pandas object has an index, a set of labels attached to its rows. sort_values orders rows by what is in a column, and the index labels travel with their rows. sort_index ignores the values and orders by the labels.
The most common use is restoring the original order after a value sort. Start with the sales table from earlier chapters:
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_units = df.sort_values("units", ascending=False)
print(by_units.index.tolist())
print(by_units.sort_index().index.tolist())The first line prints [4, 0, 3, 5, 1, 2], because each row kept its original label. The second prints [0, 1, 2, 3, 4, 5].
Text labels and the ascending flag
The default is ascending=True, as in sort_values. Labels can be any type, such as strings, dates, or integers. Here the region becomes the index:
by_region = df.set_index("region")
print(by_region.sort_index())
print(by_region.sort_index(ascending=False))The first call orders the labels East, East, North, North, South, South. The second reverses that order.
Region labels repeat, so the index is not unique. Rows that share a label are ties. The default algorithm, quicksort, does not guarantee that tied rows keep their original relative order. If that order matters, request a stable sort:
print(by_region.sort_index(kind="stable"))With kind="stable", the two North rows stay in the order North/A, North/B, as in the source data. Stable sorting is covered further in a later chapter.
Why a sorted index matters: slicing
Sorting by index is more than cosmetic. Label slicing with .loc[start:end] needs a monotonic index, meaning one that only increases or only decreases, once the index has duplicates. On an unsorted index with duplicates, pandas cannot find a well-defined range and raises an error:
try:
by_region.loc["East":"North"]
except KeyError:
print("KeyError: index is not sorted")
ordered = by_region.sort_index()
print(ordered.index.is_monotonic_increasing)
print(ordered.loc["East":"North"])After sorting, the slice returns the two East rows and the two North rows. Label slices include both endpoints, unlike positional slices.
A sorted index is also faster to look up in, because pandas can use binary search instead of scanning every label. You will notice this on large tables.
Sorting columns with axis=1
The axis argument chooses which labels to order. The default axis=0 orders rows. Setting axis=1 orders the column names:
print(df.sort_index(axis=1))
print(df.sort_index(axis=1, ascending=False).columns.tolist())The first call returns the columns in the order price, product, region, units. The second prints ['units', 'region', 'product', 'price']. This is handy for comparing two DataFrames that were built with columns in different orders.
Sorting a MultiIndex
When the index has several levels, sort_index sorts by the first level, then the second, and so on. Use level to choose a different starting level:
multi = df.set_index(["region", "product"])
print(multi.sort_index())
print(multi.sort_index(level="product"))
print(multi.sort_index(level="product", sort_remaining=False))- The first call sorts by region, then by product within each region.
- The second sorts by product first. Because
sort_remaining=Trueis the default, the other level (region) then breaks ties. - The third sorts only by product. Rows with the same product keep their relative order (a stable ordering within the product groups is the practical result, but use
kind="stable"if you depend on it).
You can also give ascending a list with one flag per level. Pass the levels you want in level, in the order you want them applied:
print(multi.sort_index(level=["region", "product"], ascending=[True, False]))This orders regions alphabetically and, inside each region, lists product B before product A.
Custom ordering with key
sort_index accepts a key function, just like sort_values. The function receives the whole index as an Index object and must return an Index of the same length. Pandas sorts by the returned values but keeps the original labels.
The default sort is case-sensitive, so uppercase letters come before lowercase ones:
s = pd.Series([1, 2, 3, 4], index=["b", "A", "c", "D"])
print(s.sort_index())
print(s.sort_index(key=lambda idx: idx.str.lower()))The first call orders the labels A, D, b, c. The second orders them A, b, c, D, and the labels still print with their original capitalization. With a MultiIndex, the key is applied to each level separately.
Missing labels
An index can contain missing values. By default sort_index puts them at the end. The na_position argument moves them:
t = pd.Series([10, 20, 30], index=[2, None, 1])
print(t.sort_index())
print(t.sort_index(na_position="first"))Because None is not an integer, pandas converts the index to floats. The first call orders the labels 1.0, 2.0, NaN. The second puts NaN first. This mirrors na_position in sort_values, but it applies to the labels, not the data.
Renumbering and other options
Two arguments you already know from sort_values also work here:
ignore_index=Truediscards the sorted labels and gives the result a fresh0..n-1index. This is rarely useful withsort_index, since you would lose the very labels you sorted by. It matters mostly for the intermediate step in a longer chain.inplace=Truemodifies the object instead of returning a new one. Prefer assigning the result to a variable, because chained expressions are easier to read and test.
Quick reference
| Goal | Call |
|---|---|
| Restore original row order | `df.sort_index()` |
| Reverse label order | `df.sort_index(ascending=False)` |
| Order column names | `df.sort_index(axis=1)` |
| Sort a MultiIndex by one level | `df.sort_index(level="product")` |
| Ignore case | `df.sort_index(key=lambda i: i.str.lower())` |
| Keep ties in input order | `df.sort_index(kind="stable")` |
| Put missing labels first | `df.sort_index(na_position="first")` |
Common mistakes
- Calling
sort_indexwhen you meantsort_values. If the index is the default0..n-1, sorting by index only restores the original order. - Forgetting to assign the result.
df.sort_index()returns a new DataFrame and leavesdfunchanged. - Slicing with
.locon an unsorted index that has duplicate labels, which raisesKeyError. - Passing a key function that returns a different length, or that returns a plain list instead of an
Index-like object. Use string accessors such asidx.str.lower()or methods likeidx.map(...).
Exercise
A DataFrame sales has a string index of region names with repeated labels, such as "North" appearing twice. You want the rows ordered from "South" down to "East" (reverse alphabetical), ignoring capitalization, with rows sharing a label kept in their original relative order. Write the call.
Show answer
sales.sort_index(ascending=False, key=lambda idx: idx.str.lower(), kind="stable") The key lowercases the labels so that "south" and "South" compare equal, ascending=False reverses the order, and kind="stable" keeps tied rows in their input order. The returned object is a new DataFrame, so assign it to a variable.
Exercise
After running by_units = df.sort_values("units", ascending=False), which call returns the rows to their original order, and why does it work even though the units column still has a missing value?
Show answer
byunits.sortindex(). The method orders by the index labels only, so the values, including NaN, play no part. Each row kept its original label (0 to 5) through the value sort.