Sub topic 9
Reading MultiIndex columns
This chapter assumes you can build a DataFrame, select columns with [] and loc, and call pivot_table with an aggfunc. It covers what a column MultiIndex is, which calls produce one, and how to select from it. The next chapter covers flattening it into plain names.
Why columns become a MultiIndex
A pandas Index holds one label per column. A MultiIndex holds a tuple of labels per column, such as ("sales", "jan"). Each position in the tuple is a level. Levels are numbered from 0 on the outside (left) and may carry names.
pivot_table builds a MultiIndex on the columns whenever the result needs more than one label per column. There are three triggers:
valuesis a list, for examplevalues=["sales", "units"].columnsis a list, for examplecolumns=["month", "channel"].aggfuncis a list, for exampleaggfunc=["sum", "count"].
Each trigger adds one level. They combine, so a list for values and a list for aggfunc gives three levels.
A first MultiIndex
The data below extends the sales table from earlier chapters with a units column and a channel column. Store A has two January rows, so pivot_table has to aggregate them.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"channel": ["web", "shop", "web", "shop"],
"sales": [60, 40, 80, 90],
"units": [6, 4, 8, 9],
})
multi = df.pivot_table(
index="store",
columns="month",
values=["sales", "units"],
aggfunc="sum",
)
print(list(multi.columns))
print(list(multi.columns.names))[('sales', 'feb'), ('sales', 'jan'), ('units', 'feb'), ('units', 'jan')]
[None, 'month']Level 0 holds the value names. It has no name, because pandas does not label it. Level 1 holds the month values and is named month, taken from the columns argument. Store A has no February rows, so its two February cells are NaN.
Level 0 groups columns. Each group repeats the same level 1 labels, and pandas stores the repeated labels once per group.
Selecting from MultiIndex columns
Selection works from the outside in. The outermost level is easy to select, and inner levels need extra syntax.
Selecting by the outer level
A single label selects every column in that group. The result is a DataFrame whose columns have lost the outer level.
print(multi["sales"].columns.tolist())['feb', 'jan']Selecting one column with a tuple
A full tuple selects one column and returns a Series. Use loc to combine it with a row label.
print(multi[("sales", "jan")].tolist())
print(multi.loc["B", ("units", "feb")])[100.0, 80.0]
9.0The values are floats because the NaN cells force the table to a float dtype.
Selecting by an inner level
multi["jan"] fails, because "jan" is not on level 0.
try:
multi["jan"]
except KeyError as err:
print("KeyError:", err)KeyError: 'jan'Two tools reach the inner level. xs (cross-section) takes a label and a level, by number or by name. pd.IndexSlice lets you write : for "any value" on the levels you don't care about.
print(multi.xs("jan", axis=1, level="month").columns.tolist())
print(multi.loc[:, pd.IndexSlice[:, "jan"]].columns.tolist())['sales', 'units']
[('sales', 'jan'), ('units', 'jan')]The two results differ in shape. xs drops the level you selected on, so only sales and units remain. IndexSlice keeps both levels, so the tuples stay intact.
| Goal | Tool | Keeps the selected level? |
|---|---|---|
| All columns under one outer label | `df["sales"]` | No, the outer level is dropped |
| One exact column | `df[("sales", "jan")]` | Returns a Series |
| One label on an inner level | `df.xs("jan", axis=1, level="month")` | No |
| Slice on any level | `df.loc[:, pd.IndexSlice[:, "jan"]]` | Yes |
Naming level 0
Because level 0 has no name, xs needs level=0. You can name the level to make the code easier to read. rename_axis returns a new DataFrame and leaves the original unchanged.
named = multi.rename_axis(columns=["measure", "month"])
print(named.xs("units", axis=1, level="measure").columns.tolist())['feb', 'jan']Inspecting levels
Four attributes help when you meet an unfamiliar table.
columns.nlevelsgives the number of levels.columns.namesgives the level names, withNonefor unnamed levels.columns.get_level_values(0)gives one label per column for level 0, with repeats.columns.levelsgives the unique labels stored for each level.
print(multi.columns.nlevels)
print(multi.columns.get_level_values(0).tolist())
print([list(level) for level in multi.columns.levels])2
['sales', 'sales', 'units', 'units']
[['sales', 'units'], ['feb', 'jan']]get_level_values matches the number of columns, so you can use it to build masks or new labels. levels holds unique values only. After you select a subset of columns, levels can still list labels that no longer appear. Call columns.remove_unused_levels() if that matters.
Multiple columns and multiple aggregations
A list for columns stacks the labels in the order you list them.
by_channel = df.pivot_table(
index="store",
columns=["month", "channel"],
values="sales",
aggfunc="sum",
)
print(list(by_channel.columns))[('feb', 'shop'), ('jan', 'shop'), ('jan', 'web')]Only combinations that occur in the data get a column. There is no ('feb', 'web') column, because no row has that pair. Missing cells inside the existing columns are still NaN, and fill_value fills them.
A list for aggfunc adds a level in front, holding the function names.
stats = df.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
print(list(stats.columns))
print(stats["count"].columns.tolist())[('sum', 'feb'), ('sum', 'jan'), ('count', 'feb'), ('count', 'jan')]
['feb', 'jan']Here values is the string "sales", so the value name does not get its own level. The result has two levels, not three.
Gotchas
valuesas a list always adds a level.values="sales"produces flat columns.values=["sales"]produces aMultiIndexwithsaleson level 0, even though there is only one value column.- Omitting
valuesalso adds a level. If you pass novalues, pandas aggregates every remaining numeric column and puts those names on level 0. - Unsorted columns break slicing.
pivot_tablereturns sorted columns, so slicing works on its output. If you reorder columns by hand or concatenate tables, slicing withslice(None)orIndexSlicecan raiseUnsortedIndexErroror aPerformanceWarning. Callsort_index(axis=1)first. - Level order follows your arguments. To change it, call
swaplevel(0, 1, axis=1)and thensort_index(axis=1)so slicing works again. - A
MultiIndexdoes not export cleanly. Writing to CSV produces header rows that other tools read badly, and many libraries expect flat names. Flatten before you hand the table on.
Check your understanding
Exercise
You run df.pivot_table(index="store", columns="month", values=["sales"], aggfunc="sum"). How many column levels does the result have, and how would you select the January column?
Show answer
Two levels, because values is a list even though it holds one name. Level 0 is sales and level 1 is the month. Select January with the tuple ("sales", "jan"), for example result[("sales", "jan")], or result["sales"]["jan"]. Passing values="sales" as a string would give a single level, so result["jan"] would work.
Exercise
Given multi from this chapter, write one expression that returns all February columns for both measures, and say what the result's column labels are.
Show answer
multi.xs("feb", axis=1, level="month") returns the February columns. The result has the columns sales and units, because xs drops the level it selected on. multi.loc[:, pd.IndexSlice[:, "feb"]] also works, but it keeps both levels and returns the tuples ('sales', 'feb') and ('units', 'feb').