创建 MultiIndex
使用 pd.MultiIndex.from_tuples 或对多个列调用 set_index,构建层次化行索引,并检查其各个级别。
创建 MultiIndex 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「创建 MultiIndex」课时是免费的吗?
是的 — 「创建 MultiIndex」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「创建 MultiIndex」这节课中我会学到什么?
使用 pd.MultiIndex.from_tuples 或对多个列调用 set_index,构建层次化行索引,并检查其各个级别。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「创建 MultiIndex」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 创建 MultiIndex
- 从 MultiIndex 选择数据
- 索引对齐与重新索引
- 排序索引的性能优势