pandas in depth · lesson 5 of 12
Parts in this lesson
Adf.set_index("store")a column becomes the row labels
Bs.loc[("Lipa", "rice")]one row of a two-level index
Cdf.reset_index()the index becomes columns again

Indexes and multi-indexes

Last updated

Every table has an index, and until now it's mostly been 0, 1, 2. In this lesson you'll choose an index on purpose, so you can look rows up by name, use the two-level index groupby makes, and learn the habit that stops a column from disappearing into the index when you least expect it.

By the end of this lesson you can

  • Make a column the index with set_index, and look rows up by it
  • Pick from a two-level index with a tuple and with xs
  • Turn an index back into columns with reset_index
  • Flatten two-level column names into single ones

An index you choose

The first two cells make the store name the index of the store list, then look Lipa up by name. Run the whole notebook; steps 1 and 2 go through it.

index.ipynb

set_index("store") moves the column into the row labels. Now stores.loc["Lipa", "town"] reads like the question you're asking. An index is worth setting when each row has a natural, unique name (a store, a date, a product code) and you'll look rows up by it. It's also how pandas lines up two tables in maths (lesson 3.1), so a / b matches stores to stores.

Lookups by index are also fast: pandas can find a label without checking every row, which matters on big tables.

Two levels

A groupby with two keys makes a MultiIndex: two levels of labels. Step through how to read and pick from one:

A two-level index. groupby(["store", "item"]) gives a two-level index: each store, and inside it each item. pandas prints each store once, like the branches of a tree.Batangasrice80sugar23Liparice68sugar19Tanauanrice59sugar15bystoreitemkilos
1 of 4 groupby(["store", "item"]) gives a two-level index: each store, and inside it each item. pandas prints each store once, like the branches of a tree.

In the notebook above:

  • by.index lists each pair as a tuple: ('Batangas', 'rice') and so on.
  • by.loc[("Lipa", "rice")] picks one with a tuple: 68.
  • by.xs("rice", level="item") takes the rice row of every store.
  • The last cell shows the other place two levels appear: columns. agg(["sum", "max"]) on a column gives column names in two levels. Joining them with "_" gives plain names, kilos_sum and kilos_max, which are easier to use and to save.

Multi-indexes are powerful but awkward. Most of the time, reset_index() and ordinary columns are clearer.

Wrong way: the column that vanished

You add up kilos by store and want to use the store names. Run it.

totals.ipynb

KeyError: 'store'. The table plainly shows the stores, but they're not a column: groupby made them the index. That's why the word store sits on a line of its own above the numbers. A later merge(on="store") or totals["store"] can't find it.

The habit: end a groupby with .reset_index() (or group with as_index=False) unless you want the index on purpose. Run the fixed version:

totals.ipynb

Check what you learned

After p = products.set_index("code"), how do you get the price of product RC25?
by has a two-level index, store and item. Which gives every store’s sugar?
t = df.groupby("store")["kilos"].sum(), then t.merge(stores, on="store") fails. What fixes it?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Data Analysis