← Back to Pandas Course | Chapter 4: Indexing & Selection | Lesson 6 of 7

MultiIndex basics

A MultiIndex gives rows two or more levels of labels, like a table with grouped row headings.

In this page:

  1. MultiIndex basics
Syntax
python
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

python
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
  1. Slicing an unsorted MultiIndex
  2. Forgetting to pass a tuple for multi-level selection
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.