Sub topic 9
Reading MultiIndex columns
This chapter assumes you can build a DataFrame, select columns with [] and loc, and use groupby with aggregation functions such as sum and count. Earlier chapters covered pivot_table. Here you learn to read the column labels it sometimes produces.
What a MultiIndex is
A MultiIndex is an index with more than one level. Each label is a tuple, such as ("sum", "jan"). Rows can have one, and so can columns. The columns get one when you ask pivot_table for more than one result per cell. This happens in two cases:
- You pass a list of aggregation functions to
aggfunc. - You pass a list of columns to
values.
Both cases add a level to the column labels. Passing a list of columns to columns also produces a MultiIndex.
Seeing one in practice
Start with the duplicate-key data from the previous chapters. Store A has two january rows.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
multi = sales.pivot_table(
index="store",
columns="month",
values="sales",
aggfunc=["sum", "count"],
)
print(multi)
print(multi.columns)The printed table has two header rows. The top row holds the function names, sum and count. The second row holds the months, feb and jan. The store label sits on its own line below, because it is the row index.
The print(multi.columns) call shows the real structure: a MultiIndex with the levels ['count', 'sum'] and ['feb', 'jan']. Each column is a pair, and the first item is the outer level.
Selecting from MultiIndex columns
The outer level works like an ordinary column name. This returns a DataFrame holding only the sum columns, with the months as its columns:
print(multi["sum"])To reach a single column, pass the full tuple, or chain the two lookups:
print(multi[("sum", "jan")])
print(multi["sum"]["jan"])Both return a Series with one value per store. The tuple form is better practice, because it does one lookup instead of two and avoids chained-indexing warnings if you later assign to the result.
To select by the inner level, for example every jan column, use xs:
print(multi.xs("jan", axis=1, level=1))Here level=1 means the second header row, and axis=1 means you are selecting columns, not rows.
Level names
Levels can have names. pivot_table does not name the function level, but it does name the second level after the column you pivoted on. Check with:
print(multi.columns.names)You get [None, 'month']. The unnamed first level is why you refer to levels by number in xs. You can also pass level="month" for the named one.
Common errors
- KeyError on a single name.
multi["jan"]fails becausejanis on the inner level. Selecting with[]only looks at the outer level. - Getting a DataFrame when you wanted a Series.
multi["sum"]returns a DataFrame. Add the inner label to get a Series. - Forgetting that the index is separate.
storeis not a column here. It is the row index, somulti["store"]raises aKeyError. - Unsorted tuple lookups. Lookups on a MultiIndex are fastest and most reliable when the labels are sorted.
pivot_tablesorts them for you, which is whyfebcomes beforejan.
Exercise
Using the multi table above, which expression returns the count of january rows for each store as a Series, and why does multi["count"] not return a Series?
Show answer
multi[("count", "jan")] returns the Series. multi["count"] selects only the outer level, so the result still has the month level as its columns and is a DataFrame with the columns feb and jan.