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:
g = df.groupby(["programme", "year"])["package"].mean()g.index # a MultiIndex of (programme, year) pairsg.loc[("Data", 2026)] # select by the tuple
Creating one
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:
mi.loc["Data"] # everything under programme = Datami.loc[("Data", 2026)] # one specific pairmi.xs(2026, level="year") # all programmes, just 2026 (inner level)# The slicers idiom for ranges across levelsidx = pd.IndexSlicemi.loc[idx["Data":"Full Stack", 2026], :]
Swapping & flattening
mi.swaplevel() # swap the two index levelsmi.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
- 01A MultiIndex has multiple index levels; each row is keyed by a tuple of labels.
- 02Multi-key groupby produces a MultiIndex automatically; set_index([...]) builds one.
- 03Always sort_index() a MultiIndex — unsorted ones are slow and can error on slices.
- 04Select with loc tuples, xs for inner levels, and pd.IndexSlice for ranges across levels.
- 05swaplevel, unstack and reset_index rearrange or flatten hierarchical data.
