Einen MultiIndex erstellen
Erstellen Sie mit pd.MultiIndex.from_tuples oder set_index für mehrere Spalten einen hierarchischen Zeilenindex und untersuchen Sie dessen Ebenen.
Einen MultiIndex erstellen ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Pandas & NumPy Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Einen MultiIndex erstellen“ kostenlos?
Ja — der vollständige Text von „Einen MultiIndex erstellen“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Pandas & NumPy Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Pandas & NumPy Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Einen MultiIndex erstellen“?
Erstellen Sie mit pd.MultiIndex.from_tuples oder set_index für mehrere Spalten einen hierarchischen Zeilenindex und untersuchen Sie dessen Ebenen. Du übst Pandas & NumPy Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Pandas & NumPy Academy zu starten?
Keine Vorkenntnisse erforderlich. Pandas & NumPy Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Einen MultiIndex erstellen“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Pandas & NumPy Academy-Lektion Code schreiben und ausführen?
Ja. Jede Pandas & NumPy Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Einen MultiIndex erstellen
- Daten aus einem MultiIndex auswählen
- Indexausrichtung und Reindexierung
- Leistungsvorteile sortierter Indizes