Skip to main content
Albero Academy

MultiIndex & Hierarchical Data

Work with multi-level row and column indexes — build them, select across levels, and flatten back to plain columns.

Chapter 12Pandas15 min readBeginner friendly
  • #Pandas
  • #MultiIndex
  • #Hierarchical

A MultiIndex gives a DataFrame more than one index level — think "programme and year" as the row key. It appears naturally after grouping on several keys, and mastering it turns awkward nested data into clean, sliceable tables.

What is a MultiIndex?

It's an index with multiple levels, so each row (or column) is identified by a tuple of labels. A two-key groupby produces one automatically:

where they come from
g = df.groupby(["programme", "year"])["package"].mean()
g.index # a MultiIndex of (programme, year) pairs
g.loc[("Data", 2026)] # select by the tuple

Creating one

set a multi-level index
mi = df.set_index(["programme", "year"]).sort_index()
# Always sort_index() a MultiIndex — unsorted ones are slow and can error on slices.

Selecting across levels

loc works with tuples, and xs (cross-section) selects on an inner level without specifying the outer:

slicing a MultiIndex
mi.loc["Data"] # everything under programme = Data
mi.loc[("Data", 2026)] # one specific pair
mi.xs(2026, level="year") # all programmes, just 2026 (inner level)
# The slicers idiom for ranges across levels
idx = pd.IndexSlice
mi.loc[idx["Data":"Full Stack", 2026], :]

Swapping & flattening

rearrange & simplify
mi.swaplevel() # swap the two index levels
mi.unstack("year") # move the year level up into columns (a grid)
mi.reset_index() # flatten the MultiIndex back into plain columns

Practice

Group by two keys to get a MultiIndex Series, then select one outer label, one exact pair, and an inner-level cross-section with xs. unstack one level into a grid, then reset_index back to flat columns.

Key takeaways

  1. 01A MultiIndex has multiple index levels; each row is keyed by a tuple of labels.
  2. 02Multi-key groupby produces a MultiIndex automatically; set_index([...]) builds one.
  3. 03Always sort_index() a MultiIndex — unsorted ones are slow and can error on slices.
  4. 04Select with loc tuples, xs for inner levels, and pd.IndexSlice for ranges across levels.
  5. 05swaplevel, unstack and reset_index rearrange or flatten hierarchical data.