Index setzen und zurücksetzen
Machen Sie mit set_index() eine Spalte zum Zeilenindex, setzen Sie ihn mit reset_index() zurück und verschaffen Sie sich einen Überblick über einen MultiIndex.
Index setzen und zurücksetzen ist eine kostenlose Pandas & NumPy Academy-Lektion auf CoddyKit. Dies ist Lektion 4 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 the DataFrame Index?
Every Pandas DataFrame has a row index — a set of labels attached to each row. The default index is a RangeIndex (0, 1, 2, …), but you can replace it with any column that acts as a natural identifier: a date, a product ID, a user ID, or any unique key. A meaningful index improves readability, enables label-based slicing, and is required for time series resampling.
import pandas as pd
df = pd.DataFrame({
'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
'sales': [100, 200, 150]
})
print('Default index:', df.index.tolist()) # [0, 1, 2]
print(df)set_index() — Promoting a Column
DataFrame.set_index('col') promotes the specified column to become the row index, removing it from the regular columns. The column's values become row labels. This is the standard way to make a DataFrame more expressive when one column acts as a natural key. A new DataFrame is returned; the original is unchanged unless inplace=True is used.
import pandas as pd
df = pd.DataFrame({
'date': ['2024-01-01', '2024-01-02', '2024-01-03'],
'sales': [100, 200, 150]
})
df = df.set_index('date')
print(df)
# sales
# date
# 2024-01-01 100
# 2024-01-02 200
# 2024-01-03 150
print(df.index) # Index(['2024-01-01', ...], dtype='object', name='date')Selecting Rows with a Custom Index
Once a meaningful column is the index, you can use .loc[label] to retrieve rows by label with clean, readable syntax — no boolean masks required. For a DatetimeIndex, you can even use partial date strings like df.loc['2024-01'] to select all rows in January 2024.
import pandas as pd
df = pd.DataFrame({
'product': ['A', 'B', 'C'],
'price': [10, 20, 30],
'stock': [100, 50, 75]
})
df = df.set_index('product')
# Access row by label
print(df.loc['B'])
# price 20
# stock 50
# Name: B, dtype: int64set_index() with Multiple Columns — MultiIndex
Passing a list of column names to set_index() creates a MultiIndex (hierarchical index). The resulting DataFrame can be accessed using tuples in .loc[]. MultiIndex is essential for grouped time series (region + date), panel data (subject + time), and any analysis requiring two-level row grouping.
import pandas as pd
df = pd.DataFrame({
'region': ['East', 'East', 'West', 'West'],
'year': [2023, 2024, 2023, 2024],
'revenue': [100, 150, 200, 220]
})
df = df.set_index(['region', 'year'])
print(df)
# revenue
# region year
# East 2023 100
# 2024 150
# West 2023 200
# 2024 220
print(df.loc[('East', 2024)]) # revenue = 150drop= Parameter in set_index()
By default, set_index('col') removes the column from the DataFrame's regular columns once it becomes the index. Pass drop=False to keep the column in place while also using it as the index. This is sometimes useful when you want label-based access but also need the column available for computations in the regular column space.
import pandas as pd
df = pd.DataFrame({'id': [1, 2, 3], 'value': [10, 20, 30]})
# Keep 'id' as both index and column
df_with_both = df.set_index('id', drop=False)
print(df_with_both)
# id value
# id
# 1 1 10
# 2 2 20
# 3 3 30reset_index() — Moving Index Back to Column
reset_index() is the inverse of set_index(): it moves the current row index back into a regular column and replaces the index with the default RangeIndex. This is commonly needed after a groupby().agg() or after operations that leave you with a meaningful index you need to use as a column in further processing.
import pandas as pd
df = pd.DataFrame({'sales': [100, 200]}, index=['East', 'West'])
df.index.name = 'region'
reset = df.reset_index()
print(reset)
# region sales
# 0 East 100
# 1 West 200
print(reset.index.tolist()) # [0, 1] — default RangeIndex restoredreset_index(drop=True)
Passing drop=True to reset_index() discards the current index entirely instead of moving it to a column. Use this when the current index holds no meaningful information (e.g., after filtering rows, the index has gaps like 0, 3, 7) and you just want a clean sequential index starting from 0.
import pandas as pd
df = pd.DataFrame({'x': [10, 20, 30, 40, 50]})
filtered = df[df['x'] > 15]
print('Filtered index:', filtered.index.tolist()) # [1, 2, 3, 4]
# Drop the old index — don't move it to a column
clean = filtered.reset_index(drop=True)
print('Clean index:', clean.index.tolist()) # [0, 1, 2, 3]reset_index() After groupby
After calling groupby().agg(), the groupby keys become the index. Calling reset_index() converts them back to regular columns, giving a flat tabular result that is easier to work with, merge, or export. This is one of the most common uses of reset_index() in practice.
import pandas as pd
df = pd.DataFrame({
'dept': ['Eng', 'HR', 'Eng', 'Sales', 'HR'],
'salary': [90000, 50000, 80000, 70000, 55000]
})
# After groupby, dept becomes the index
agg = df.groupby('dept')['salary'].mean()
print(type(agg), agg.index.tolist())
# dept is the index
# Reset makes dept a regular column again
result = agg.reset_index()
result.columns = ['dept', 'avg_salary']
print(result)rename_axis() for Index Name
When the row index doesn't have a name, or when you want to rename it for clarity, use df.rename_axis('new_name') (for the row index) or df.rename_axis('col_name', axis=1) (for the column axis). Giving the index a meaningful name makes the output more self-documenting, especially when exporting to CSV where the index name becomes a column header.
import pandas as pd
df = pd.DataFrame({'sales': [100, 200, 300]}, index=['A', 'B', 'C'])
print(df.index.name) # None
# Name the index
df = df.rename_axis('region')
print(df)
# sales
# region
# A 100
# B 200
# C 300Reindexing to Fill Gaps
DataFrame.reindex(new_index) reshapes the DataFrame to match a new index, filling positions that exist in the new index but not in the original data with NaN. This is used to align DataFrames to a common complete index — for example, ensuring every month in a year appears even if no data exists for some months.
import pandas as pd
df = pd.DataFrame({
'month': ['Jan', 'Mar', 'Jun'],
'revenue': [100, 200, 300]
}).set_index('month')
all_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
complete = df.reindex(all_months)
print(complete)
# revenue
# Jan 100.0
# Feb NaN <- filled with NaN
# Mar 200.0
# Apr NaN
# May NaN
# Jun 300.0MultiIndex reset_index and Level Selection
For a MultiIndex DataFrame, reset_index() moves all levels back to columns by default. Pass level= to reset only specific levels. This is useful when you want to keep one level as the index (e.g., keep the date as the index) and move only the other level to a column.
import pandas as pd
df = pd.DataFrame(
{'revenue': [100, 150, 200, 220]},
index=pd.MultiIndex.from_tuples(
[('East', 2023), ('East', 2024), ('West', 2023), ('West', 2024)],
names=['region', 'year']
)
)
# Reset only the 'year' level, keep 'region' as index
df2 = df.reset_index(level='year')
print(df2)
# year revenue
# region
# East 2023 100
# East 2024 150
# West 2023 200
# West 2024 220Quick Check
Test your understanding of setting and resetting the index.
Lesson Recap
In this lesson you learned: set_index('col') promotes a column to the row index for label-based access, passing a list creates a MultiIndex, and reset_index() moves the index back to a column (use drop=True to discard it instead). Use reindex() to align to a complete target index filling missing positions with NaN. These techniques are foundational for the GroupBy and Merging lessons ahead.
Häufig gestellte Fragen
Ist die Lektion „Index setzen und zurücksetzen“ kostenlos?
Ja — der vollständige Text von „Index setzen und zurücksetzen“ 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 „Index setzen und zurücksetzen“?
Machen Sie mit set_index() eine Spalte zum Zeilenindex, setzen Sie ihn mit reset_index() zurück und verschaffen Sie sich einen Überblick über einen MultiIndex. 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 4 von 4.
Wie lange dauert die Lektion „Index setzen und zurücksetzen“?
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
- Nach Spaltenwerten sortieren
- Nach dem Index sortieren
- Werte rangordnen
- Index setzen und zurücksetzen