Creating a MultiIndex
Build a hierarchical row index with pd.MultiIndex.from_tuples or set_index on multiple columns, and inspect its levels.
Creating a MultiIndex is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a MultiIndex?
A MultiIndex (also called a hierarchical index) allows a Pandas DataFrame or Series to have multiple levels of row labels. Think of it as a composite key in a database: instead of identifying a row by a single label, you identify it by a tuple like (country, city) or (year, quarter). MultiIndexes are essential for representing panel data, cross-sectional time series, and any dataset with a natural two-level grouping structure.
import pandas as pd
# A simple example: sales by country and city
data = {
'sales': [100, 200, 150, 300, 80, 120]
}
index = pd.MultiIndex.from_tuples(
[('USA', 'New York'), ('USA', 'Chicago'),
('UK', 'London'), ('UK', 'Manchester'),
('DE', 'Berlin'), ('DE', 'Munich')],
names=['country', 'city']
)
df = pd.DataFrame(data, index=index)
print(df)Creating a MultiIndex with from_tuples
pd.MultiIndex.from_tuples(list_of_tuples, names=) is the most explicit way to create a MultiIndex. Each tuple becomes one row label, and its elements become the levels. The names parameter assigns a label to each level (e.g. ['year', 'quarter']). This method is useful when you have a pre-built list of composite keys that you want to use as the row index.
import pandas as pd
# Multi-level time index: year x quarter
tuples = [
(2022, 'Q1'), (2022, 'Q2'), (2022, 'Q3'), (2022, 'Q4'),
(2023, 'Q1'), (2023, 'Q2'), (2023, 'Q3'), (2023, 'Q4')
]
mi = pd.MultiIndex.from_tuples(tuples, names=['year', 'quarter'])
revenue = [120, 135, 145, 160, 130, 148, 162, 175]
df = pd.Series(revenue, index=mi, name='revenue_M')
print(df)Creating a MultiIndex with from_product
pd.MultiIndex.from_product(iterables, names=) creates a MultiIndex from the Cartesian product of multiple lists — every combination of elements from the input lists. This is the most convenient method when all combinations of levels should exist in your data. For example, all combinations of 3 years × 4 quarters × 5 regions creates a 60-row balanced panel automatically.
import pandas as pd
import numpy as np
years = [2021, 2022, 2023]
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
# Cartesian product: 3 years x 4 quarters = 12 combinations
mi = pd.MultiIndex.from_product([years, quarters], names=['year', 'quarter'])
print('Number of index entries:', len(mi))
print('First 6 entries:', mi[:6].tolist())
# Create a DataFrame with this index
df = pd.DataFrame({'revenue': np.random.randint(100, 200, 12)}, index=mi)
print('\n', df.head())Creating a MultiIndex with set_index
The most common way to create a MultiIndex in practice is to start with a regular DataFrame that has grouping columns, then call df.set_index([col1, col2]). This promotes those columns from data columns into index levels. The result is the same as if you had built the index from scratch with from_tuples, but it takes only one line starting from tabular data.
import pandas as pd
# Start with a flat DataFrame
df_flat = pd.DataFrame({
'country': ['USA', 'USA', 'UK', 'UK', 'DE', 'DE'],
'year': [2022, 2023, 2022, 2023, 2022, 2023],
'gdp_bn': [25000, 26000, 3100, 3200, 4200, 4350]
})
# Promote two columns to a MultiIndex
df = df_flat.set_index(['country', 'year'])
print(df)
print('\nIndex type:', type(df.index).__name__)
print('Index names:', df.index.names)Inspecting MultiIndex Levels
A MultiIndex stores its data in levels (the unique values at each level) and codes (integer pointers into the level arrays). Inspect the levels with df.index.levels or df.index.get_level_values(level). Use df.index.nlevels to check how many levels exist. The names attribute lists the name assigned to each level — set these with df.index.set_names(['level0', 'level1']).
import pandas as pd
df_flat = pd.DataFrame({
'country': ['USA', 'USA', 'UK', 'UK'],
'year': [2022, 2023, 2022, 2023],
'gdp': [25000, 26000, 3100, 3200]
})
df = df_flat.set_index(['country', 'year'])
print('Number of levels:', df.index.nlevels)
print('Level names:', df.index.names)
print('Level 0 values:', df.index.get_level_values(0).tolist())
print('Level 1 values:', df.index.get_level_values(1).tolist())
print('Unique level 0:', df.index.get_level_values('country').unique().tolist())MultiIndex on Columns
A MultiIndex can also be applied to columns, creating a hierarchy of column labels. This is common when you store multiple metrics for each category in a pivot-style layout — for example, (revenue, Q1), (revenue, Q2), (cost, Q1), (cost, Q2). Access columns with a MultiIndex the same way you access rows — using tuples. Create a column MultiIndex with pd.MultiIndex.from_product and assign it to df.columns.
import pandas as pd
import numpy as np
# Create a DataFrame with MultiIndex columns
metrics = ['revenue', 'cost']
quarters = ['Q1', 'Q2', 'Q3', 'Q4']
col_index = pd.MultiIndex.from_product([metrics, quarters], names=['metric', 'quarter'])
data = np.random.randint(50, 200, size=(3, 8))
df = pd.DataFrame(data, columns=col_index, index=['USA', 'UK', 'DE'])
df.index.name = 'country'
print(df)MultiIndex After GroupBy Aggregation
When you call groupby([col1, col2]).agg(...), the resulting DataFrame has a MultiIndex on its rows (the two groupby keys become the two index levels) and potentially a MultiIndex on its columns (if you aggregate multiple metrics). This is the most common way to encounter a MultiIndex in everyday data analysis — understanding how to navigate it is essential for working with groupby results.
import pandas as pd
import seaborn as sns
tips = sns.load_dataset('tips')
# Two-key groupby creates a MultiIndex on rows
result = tips.groupby(['day', 'time'])['total_bill'].agg(['mean', 'count'])
print(result)
print('\nIndex type:', type(result.index).__name__)
print('Index names:', result.index.names)Swapping and Reordering Levels
Use df.swaplevel() to swap two index levels, and df.reorder_levels([...]) to change the order of all levels. Reordering is useful when you want to slice by an inner level first, or when two DataFrames have their index levels in different order and need to be aligned before merging. After reordering, always call sort_index() to restore lexicographic order for efficient slicing.
import pandas as pd
import seaborn as sns
tips = sns.load_dataset('tips')
result = tips.groupby(['day', 'time'])['total_bill'].mean()
print('Original levels:', result.index.names)
# Swap so time is the outer level
swapped = result.swaplevel().sort_index()
print('\nSwapped levels:', swapped.index.names)
print(swapped.head())Checking and Sorting a MultiIndex
Slicing into a MultiIndex is only efficient when the index is sorted lexicographically. Check whether the index is sorted with df.index.is_monotonic_increasing. If it returns False, sort with df.sort_index(). An unsorted MultiIndex triggers a PerformanceWarning on slice operations and can return incorrect results in some edge cases — always sort after creating or modifying a MultiIndex.
import pandas as pd
# Create an unsorted MultiIndex deliberately
tuples = [('B', 2), ('A', 1), ('B', 1), ('A', 2)]
mi = pd.MultiIndex.from_tuples(tuples, names=['letter', 'num'])
df = pd.DataFrame({'value': [10, 20, 30, 40]}, index=mi)
print('Is sorted:', df.index.is_monotonic_increasing)
print('Before sorting:')
print(df)
df_sorted = df.sort_index()
print('\nAfter sorting:')
print(df_sorted)
print('Is sorted:', df_sorted.index.is_monotonic_increasing)Resetting a MultiIndex to Columns
Call df.reset_index() to convert all index levels back into regular columns, leaving the DataFrame with a plain integer RangeIndex. This is a common pattern after groupby aggregations: compute the grouped summary with a MultiIndex, then reset the index to get a flat DataFrame suitable for further Pandas operations, merging, or export to CSV. Use reset_index(level='name') to reset only one level of a two-level index.
import pandas as pd
import seaborn as sns
tips = sns.load_dataset('tips')
result = tips.groupby(['day', 'time'])['total_bill'].mean()
print('MultiIndex result:')
print(result.head(4))
# Flatten back to a regular DataFrame
flat = result.reset_index()
print('\nFlattened DataFrame:')
print(flat.head(4))
print('Index type:', type(flat.index).__name__)When to Use a MultiIndex
Use a MultiIndex when your data has a natural hierarchical structure: time series with sub-daily granularity (date + hour), panel data (entity + time period), or nested groupings (country + region + city). Avoid MultiIndexes for simple two-column group keys where a flat DataFrame with separate columns is equally readable. If you find yourself constantly calling reset_index() just to access data, that is a sign the MultiIndex is not adding value in your workflow.
Quick Check
Test your understanding of MultiIndex creation from this lesson.
Lesson Recap
In this lesson you learned: MultiIndexes provide hierarchical row (or column) labels using tuples, created with from_tuples, from_product, or set_index on multiple columns, and always sorted for efficient slicing. Next up we explore how to select data from a MultiIndex using .loc, tuples, slices, and the IndexSlice helper.
Frequently asked questions
Is the “Creating a MultiIndex” lesson free?
Yes — the full text of “Creating a MultiIndex” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating a MultiIndex”?
Build a hierarchical row index with pd.MultiIndex.from_tuples or set_index on multiple columns, and inspect its levels. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating a MultiIndex” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.