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.
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:
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.indexlists 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_sumandkilos_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.
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:
Check what you learned
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.
- pandas: MultiIndex / advanced indexing: two-level indexes, tuples, xs and slicing
- pandas: pandas.DataFrame.set_index: making a column the index
- pandas: pandas.DataFrame.reset_index: the index back into columns