skip to content

In pandas, a sales frame indexed by (region, quarter) raises UnsortedIndexError on sales.loc[pd.IndexSlice[:, 'Q1':'Q2'], :]; why, and how do you select quarters across regions?

level: seniorimportance: should knowfreq 30%

answer

  1. tuples go across levels
  2. lists go down a level
  3. lexsort depth
  4. sort_index before range slicing
  5. xs with level=

basics

~20 s

A range slice inside a MultiIndex level needs the index lexsorted at least to that level; set_index on unsorted rows is not, so pandas raises UnsortedIndexError. Call sort_index() first, or use xs('Q2', level='quarter') or a list of quarters.

solid answer

~40 s

On a MultiIndex, a **tuple** is one key across levels, `sales.loc[('West', 'Q2')]`, and `pd.IndexSlice` builds per-level selectors: `sales.loc[pd.IndexSlice[:, 'Q1':'Q2'], :]`. A *range* within a level is resolved by searching sorted codes, so pandas requires the index to be lexsorted at least as deep as that level; a frame built with `set_index(['region', 'quarter'])` from unsorted rows has lexsort depth 0 and raises `UnsortedIndexError`, a `KeyError` subclass. Exact labels and lists still work unsorted: `sales.xs('Q2', level='quarter')` returns Q2 for every region with the quarter level dropped (`drop_level=False` keeps it), and `pd.IndexSlice[:, ['Q1', 'Q2']]` works too. For ranges, call `sort_index()` once and check `index.is_monotonic_increasing`. Always pass the column selector, `, :`, so pandas cannot read the second key as columns.

code

python · 19 lines
python
import pandas as pd

sales = pd.DataFrame({
    "region": ["West", "East", "West", "East", "West", "East"],
    "quarter": ["Q2", "Q1", "Q1", "Q3", "Q3", "Q2"],
    "revenue": [120, 95, 110, 101, 130, 99],
}).set_index(["region", "quarter"])
idx = pd.IndexSlice

print(sales.index.is_monotonic_increasing)
try:
    sales.loc[idx[:, "Q1":"Q2"], :]
except pd.errors.UnsortedIndexError as err:
    print("UnsortedIndexError:", err)

print(sales.xs("Q2", level="quarter"))          # exact label: fine unsorted

sales = sales.sort_index()
print(sales.loc[idx[:, "Q1":"Q2"], "revenue"])   # range: fine once sorted

go deeper

for a junior

Recall that a tuple is one key across the levels of a MultiIndex and that loc with a bare label matches only the first level.

for a middle

Explain pd.IndexSlice and slice(None) for inner levels, tuples versus lists, and what xs with level= and drop_level= return.

for a senior

Diagnose UnsortedIndexError from lexsort depth, fix it with sort_index after set_index, and always pass the column selector so a tuple row key cannot be read as columns.

for a principal

Treat MultiIndex use as a team trade-off: it makes per-level selection concise but adds sorting and ambiguity rules, so decide where a flat frame with masks would be easier to read.

## Keys on a MultiIndex: tuples and lists A **MultiIndex** is a row index with several levels, here `region` and `quarter`, typically created with `set_index(["region", "quarter"])` on a sales table. Selecting from it turns on two Python container types, and the user guide states the rule directly: **tuples go horizontally (traversing levels), lists go vertically (scanning levels)**. - `sales.loc[("West", "Q2")]` — one complete key, one row (returned as a Series of that row's columns). - `sales.loc["West"]` — a partial key on the **first** level; returns West's rows with the region level dropped. - `sales.loc[[("West", "Q2"), ("East", "Q1")]]` — a list of tuples: several complete keys. - `sales.loc[(["West", "East"], ["Q2", "Q1"]), :]` — a tuple of lists: every combination of those values that exists, which is a different selection. - `sales.loc["Q2"]` raises `KeyError`: a bare label is matched against the first level only. ## pd.IndexSlice and slice(None) To select on an inner level you need a selector for every level before it. `slice(None)` means "all of this level", and `pd.IndexSlice` lets you write the same thing with ordinary `:` syntax: ```python idx = pd.IndexSlice sales.loc[(slice(None), "Q2"), :] # Q2 for every region sales.loc[idx[:, "Q2"], :] # the same, more readable sales.loc[idx[:, ["Q1", "Q2"]], :] # a list inside a level sales.loc[idx[:, "Q1":"Q2"], :] # a range inside a level: needs a sorted index ``` As with any label slice, both ends of `"Q1":"Q2"` are included. ## Why ranges need a sorted index pandas resolves a range inside a level by locating its start and end in the level's sorted codes, which only works if the index is **lexsorted** to at least that depth. The **lexsort depth** is the number of leading levels that are sorted. `set_index` keeps the rows in their original order; it does not sort. So a table loaded in arrival order produces an index with lexsort depth 0, and: 1. A range on any level raises `UnsortedIndexError: MultiIndex slicing requires the index to be lexsorted: slicing on levels [1], lexsort depth 0`. 2. A tuple range such as `sales.loc[("East", "Q1"):("West", "Q1")]` raises `UnsortedIndexError: Key length (2) was greater than MultiIndex lexsort depth (0)`. 3. Exact labels, lists and `slice(None)` still work, but the user guide warns that indexing an unsorted MultiIndex can be inefficient and may show a `PerformanceWarning`. `UnsortedIndexError` subclasses `KeyError`, so a broad `except KeyError` swallows it, which hides the real cause. The fix is one call: `sales = sales.sort_index()`, after which `sales.index.is_monotonic_increasing` is `True` and range slices on any level work. ## xs for one level `DataFrame.xs` takes a key and a `level` and is often the clearest way to pull a cross-section: | Call | Result | |---|---| | `sales.xs("Q2", level="quarter")` | Q2 rows for every region, quarter level dropped | | `sales.xs("Q2", level="quarter", drop_level=False)` | the same rows, both levels kept | | `sales.xs("Q2", level=1)` | the same as the first, the level given by position | | `sales.xs(("West", "Q2"))` | one complete key | | `sales.xs(["West", "East"], level="region")` | `TypeError`: list keys are not supported in `xs` | `drop_level=True` is the default, which is convenient for reading and surprising when the result is concatenated back, because the dropped level is gone. `xs` selects exact labels only; for ranges or lists use `loc` with `pd.IndexSlice`. ## The ambiguous two-key form `sales.loc["West", "Q2"]` looks like a row key across two levels, but `loc` with two comma-separated keys normally means **row, column**. `sales.loc["West", "revenue"]` therefore returns West's revenue by quarter, while `sales.loc["West", "Q2"]` happens to resolve as a row key only because no column is named `Q2`. The user guide's advice is to specify both axes: write the tuple and the column selector explicitly, `sales.loc[("West", "Q2"), :]` or `sales.loc[idx["West", "Q2"], "revenue"]`, and the meaning cannot flip when someone adds a column. ## Checklist 1. Sort once after `set_index` if you will range-slice: `sort_index()`. 2. Use tuples for one key, lists for several, `pd.IndexSlice` for per-level selectors. 3. Always give the column selector (`, :`) when the row key is a tuple or slice. 4. Reach for `xs(level=...)` for a single label on an inner level. 5. Catch `UnsortedIndexError` by name, or better, sort before slicing, rather than relying on a broad `except KeyError`. Building the MultiIndex itself (`set_index`, `MultiIndex.from_product`, `reset_index`) is covered with axis labels.

  • What is the difference between sales.loc[[('West', 'Q2'), ('East', 'Q1')]] and sales.loc[(['West', 'East'], ['Q2', 'Q1']), :]?
    The list of tuples names two complete keys and returns exactly those two rows. The tuple of lists gives a set of values per level and returns every existing combination, here four rows: West Q2, West Q1, East Q2 and East Q1. Tuples traverse levels; lists scan within a level.
  • Why check sales.index.is_monotonic_increasing after set_index instead of assuming the index is sorted?
    `set_index` keeps the rows in their existing order; it does not sort. Data loaded in arrival order therefore yields lexsort depth 0, and range slices on the MultiIndex raise `UnsortedIndexError`. `is_monotonic_increasing` tells you whether `sort_index()` is needed before slicing.

  • sales.loc['Q2'] selects the Q2 rows of every region.
  • UnsortedIndexError means the index has duplicate keys.
  • set_index(['region', 'quarter']) sorts the resulting MultiIndex.
  • A list of tuples and a tuple of lists select the same rows.
  • xs('Q2', level='quarter') keeps the quarter level by default.