MultiIndex Basics
A MultiIndex is an index with several levels, like (country, city) or (year, month). You've already met one: grouping by two columns produces it. It lets a flat table represent hierarchical data, and once you know a few tools it's easy to work with.
Creating a MultiIndex
The usual way is set_index() with a list of columns:
import pandas as pd
shops = pd.DataFrame({
"country": ["NL", "NL", "NL", "BE", "BE"],
"city": ["Utrecht", "Leiden", "Delft", "Ghent", "Bruges"],
"staff": [12, 8, 9, 15, 6],
"revenue_k": [410, 260, 300, 520, 190],
}).set_index(["country", "city"])
print(shops)
print(shops.index.nlevels, shops.index.names) staff revenue_k
country city
NL Utrecht 12 410
Leiden 8 260
Delft 9 300
BE Ghent 15 520
Bruges 6 190
2 ['country', 'city']
The outer level (country) is printed only when it changes, which makes the hierarchy easy to see.
Selecting with loc
Selecting by the outer level returns all its rows; a tuple selects a full key:
import pandas as pd
shops = pd.DataFrame({
"country": ["NL", "NL", "NL", "BE", "BE"],
"city": ["Utrecht", "Leiden", "Delft", "Ghent", "Bruges"],
"staff": [12, 8, 9, 15, 6],
"revenue_k": [410, 260, 300, 520, 190],
}).set_index(["country", "city"])
print(shops.loc["BE"])
print(shops.loc[("NL", "Delft"), "revenue_k"])
print(shops.loc[[("NL", "Leiden"), ("BE", "Ghent")]]) staff revenue_k
city
Ghent 15 520
Bruges 6 190
300
staff revenue_k
country city
NL Leiden 8 260
BE Ghent 15 520
Cross-sections with xs()
To select by an inner level, xs() (cross-section) is the clearest tool:
import pandas as pd
sales = pd.DataFrame({
"year": [2023, 2023, 2023, 2024, 2024, 2024],
"quarter": ["Q1", "Q2", "Q3", "Q1", "Q2", "Q3"],
"units": [140, 165, 190, 158, 171, 205],
}).set_index(["year", "quarter"])
print(sales.xs("Q2", level="quarter"))
print(sales.xs(2024, level="year")["units"].sum()) units
year
2023 165
2024 171
534
Aggregating by level
groupby(level=...) groups by an index level, no column needed:
import pandas as pd
shops = pd.DataFrame({
"country": ["NL", "NL", "NL", "BE", "BE"],
"city": ["Utrecht", "Leiden", "Delft", "Ghent", "Bruges"],
"staff": [12, 8, 9, 15, 6],
"revenue_k": [410, 260, 300, 520, 190],
}).set_index(["country", "city"])
print(shops.groupby(level="country").sum())
share = shops["revenue_k"] / shops.groupby(level="country")["revenue_k"].transform("sum")
print(share.round(2)) staff revenue_k
country
BE 21 710
NL 29 970
country city
NL Utrecht 0.42
Leiden 0.27
Delft 0.31
BE Ghent 0.73
Bruges 0.27
Name: revenue_k, dtype: float64
Sorting, swapping and flattening
import pandas as pd
shops = pd.DataFrame({
"country": ["NL", "NL", "BE"],
"city": ["Utrecht", "Leiden", "Ghent"],
"staff": [12, 8, 15],
}).set_index(["country", "city"])
print(shops.sort_index())
print(shops.swaplevel().sort_index())
print(shops.reset_index()) staff
country city
BE Ghent 15
NL Leiden 8
Utrecht 12
staff
city country
Ghent BE 15
Leiden NL 8
Utrecht NL 12
country city staff
0 NL Utrecht 12
1 NL Leiden 8
2 BE Ghent 15
sort_index() sorts by every level, which also makes slicing faster. swaplevel() swaps the order of the levels, and reset_index() flattens everything back to ordinary columns, often the simplest option when a MultiIndex gets in the way.
MultiIndex columns
Columns can have levels too. agg() with several functions per column produces them. Flatten them by joining the level names:
import pandas as pd
runs = pd.DataFrame({
"runner": ["Lu", "Lu", "Mo", "Mo", "Mo"],
"km": [5.0, 10.0, 8.0, 12.0, 6.0],
"minutes": [27, 58, 41, 66, 30],
})
stats = runs.groupby("runner").agg({"km": ["sum", "max"], "minutes": ["mean"]}).round(1)
print(stats)
print(stats.columns.to_list())
stats.columns = ["_".join(col) for col in stats.columns]
print(stats) km minutes
sum max mean
runner
Lu 15.0 10.0 42.5
Mo 26.0 12.0 45.7
[('km', 'sum'), ('km', 'max'), ('minutes', 'mean')]
km_sum km_max minutes_mean
runner
Lu 15.0 10.0 42.5
Mo 26.0 12.0 45.7
Tip: Named aggregation (
agg(km_sum=("km", "sum"))) avoids MultiIndex columns in the first place.
Test yourself
How do you select the row with keys ("NL", "Delft") from a two-level index?
- df.loc["NL", "Delft"]
- df.loc[("NL", "Delft")]
- df.iloc[("NL", "Delft")]
- df["NL"]["Delft"]
Which method selects all rows where the inner level quarter is "Q2"?
- df.loc["Q2"]
- df.xs("Q2", level="quarter")
- df.inner("Q2")
- df.query("Q2")
What is the simplest way to turn a MultiIndex back into ordinary columns?
- flatten()
- reset_index()
- drop_index()
- unstack()