MultiIndex basics
A MultiIndex gives rows two or more levels of labels, like a table with grouped row headings.
In this page:
Syntax
df = df.set_index(["column1", "column2"])
df.loc[(value1, value2)]
MultiIndex basics
Set several columns as the index with set_index([...]) to create hierarchical rows. Select an outer level with loc, or an inner level with xs. Hierarchical indexes appear naturally after groupby with multiple keys.
Note:
sort_index() makes MultiIndex slicing faster and more predictable.
Example: MultiIndex basics
import pandas as pd
df = pd.DataFrame({
"country": ["FR", "FR", "JP", "JP"],
"year": [2022, 2023, 2022, 2023],
"gdp": [2.9, 3.0, 4.2, 4.3],
}).set_index(["country", "year"]).sort_index()
print(df)
print(df.loc["JP"])
print(df.loc[("FR", 2023), "gdp"])
# Output:
# gdp
# country year
# FR 2022 2.9
# 2023 3.0
# JP 2022 4.2
# 2023 4.3
# gdp
# year
# 2022 4.2
# 2023 4.3
# 3.0
Related Topics
Common Mistakes
- Slicing an unsorted MultiIndex
- Forgetting to pass a tuple for multi-level selection
- Overusing MultiIndex when columns would do
Chapter Summary
- set_index with a list builds a MultiIndex
- loc picks outer levels
- xs picks any level
- Sort the index first
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: