~/learn/Pandas · Merging & reshaping

MultiIndex basics

Work with grouped results that have more than one key.

8 min readlesson 6 of 13multiindexunstackxs

why this matters

Grouping by two things — country and category, say — gives a result with two keys. Knowing how to navigate it saves a lot of confusion.

Grouping by two keys produces a MultiIndex — one index level per key. It is not a different object, just an index with tuples.

python · editable
loading editor…

Select a level with .loc and a tuple, or use xs to slice on an inner level directly.

python · editable
loading editor…

Try it: Get the revenue for UK Hardware only.

unstack pivots an index level into columns and reset_index flattens everything back into plain columns — usually the last step before charting or exporting.

python · editable
loading editor…

Three shapes of the same data

groupby(["country","category"]).sum()
 → index has two levels

reset_index()  → back to plain columns
unstack()      → second level becomes columns

Pro tip

When a grouped result feels awkward to work with, reset_index() turns it straight back into an ordinary frame.

key takeaways

  • Grouping by several keys creates a MultiIndex.
  • reset_index flattens it back to columns.
  • unstack pivots an index level into columns.

check your understanding

You grouped by two columns and want a plain frame with normal columns again. What do you call?

free practice

Build confidence with a question you can solve without Pro.