Python Pandas: reset_index, set_index, and MultiIndex
Learn how to move columns into the index with set_index(), return the index to columns with reset_index(), and work with MultiIndex levels in pandas.

set_index() moves columns into a DataFrame's row index, reset_index() moves the index back into columns, and a MultiIndex provides hierarchical row labels when you use more than one column as the key. This guide explains the syntax, behavior, and edge cases for these pandas operations.
Every pandas DataFrame carries an index that controls how rows are identified and aligned. Most DataFrames start with a RangeIndex of sequential integers, but real data often needs a meaningful key such as a timestamp, an ID, or a composite of several columns. The sections below show how to move columns into the index and back out again, build a MultiIndex, and avoid common mistakes.
What the index actually controls
Before changing an index, it helps to know what it is used for. The index is the row label set that pandas uses for:
- alignment during arithmetic operations
- lookup with
.loc[] groupby()operations on index levels- joining DataFrames on their indexes, for example with
merge(..., left_index=True, right_index=True) - time series resampling when the index is a
DatetimeIndex
A default RangeIndex is just a row counter. It has no relationship to the data, so operations that depend on row identity, such as joining on an index or slicing a date range, require a meaningful index. set_index() and reset_index() are how you move data between the column axis and the row label axis.
Moving a column into the index with set_index()
import pandas as pd
df = pd.DataFrame({
"order_id": [1001, 1002, 1003],
"customer": ["Ada", "Grace", "Alan"],
"amount": [250.0, 180.0, 310.0],
})
keyed = df.set_index("order_id")
print(keyed) customer amount
order_id
1001 Ada 250.0
1002 Grace 180.0
1003 Alan 310.0By default, set_index() returns a new DataFrame with the chosen column removed from the columns and promoted to the row index. The original DataFrame is unchanged unless you pass inplace=True, which makes the method return None; assigning the result is generally clearer and avoids that pitfall.
To keep the column in the DataFrame while also using it as the index, pass drop=False.
keyed = df.set_index("order_id", drop=False)set_index() accepts a single column name, a list of names, or a pandas Index object. Passing more than one column name creates a MultiIndex, covered below.
Moving the index back to columns with reset_index()
restored = keyed.reset_index()
print(restored) order_id customer amount
0 1001 Ada 250.0
1 1002 Grace 180.0
2 1003 Alan 310.0reset_index() takes the current index and writes it back as a column, then replaces the index with a fresh RangeIndex. The column name comes from the index name; if the index has no name, the new column is named index.
To discard the index instead of keeping it as a column, pass drop=True.
no_index = keyed.reset_index(drop=True)This is useful when the index was only a temporary label and carries no data you need to preserve.
Building and using a MultiIndex
A MultiIndex has more than one level, so each row is identified by a tuple of labels rather than a single value. The most common way to create one is to pass a list of column names to set_index().
sales = pd.DataFrame({
"region": ["East", "East", "West", "West"],
"month": ["Jan", "Feb", "Jan", "Feb"],
"revenue": [1200, 1350, 980, 1100],
})
hier = sales.set_index(["region", "month"])
print(hier) revenue
region month
East Jan 1200
Feb 1350
West Jan 980
Feb 1100The levels are ordered by the list passed to set_index(). The first level is the outermost, and the second is nested inside it. This ordering matters for .loc[] slicing and for reset_index().
To select rows from a MultiIndex, pass a tuple to .loc[].
print(hier.loc[("East", "Feb")])revenue 1350
Name: (East, Feb), dtype: int64You can also select all rows for one outer level with partial indexing.
print(hier.loc["West"]) revenue
month
Jan 980
Feb 1100reset_index() on a MultiIndex returns all levels to columns by default and names them from the level names.
flat = hier.reset_index()
print(flat) region month revenue
0 East Jan 1200
1 East Feb 1350
2 West Jan 980
3 West Feb 1100To reset only some levels, pass the level parameter with a level name or position.
partial = hier.reset_index(level="month")
print(partial) month revenue
region
East Jan 1200
East Feb 1350
West Jan 980
West Feb 1100This keeps region as the index and moves month back to a column. The result is still a MultiIndex if more than one level remains, or a single-level index if only one remains.
Parameters that change behavior
| Parameter | Applies to | Effect |
|---|---|---|
drop | both | For set_index(), False keeps the original column; for reset_index(), True discards the index instead of writing it back. |
inplace | both | Mutates the DataFrame and returns None; assigning the result is usually clearer. |
level | reset_index | Resets only the named levels, leaving the other levels as the index. |
col_level | reset_index | Inserts the index labels into a specified column level when the columns have a MultiIndex. |
col_fill | reset_index | Names the remaining column levels when the columns have a MultiIndex and col_level is used. |
append | set_index | Adds the new level without removing the existing index. |
verify_integrity | set_index | Raises if the new index contains duplicates. |
append=True is useful when you want to keep the current index and add a level on top of it.
hier2 = df.set_index("customer", append=True)verify_integrity=True raises a ValueError if the resulting index has duplicate labels. This is a useful safety check when duplicate keys would break later lookups.
Performance and memory implications
By default, set_index() and reset_index() each return a new DataFrame, so repeated round-trips can be costly for large data. For a few thousand rows this is rarely a problem; for millions of rows it may take noticeable time and memory.
The bigger cost is usually what happens after the index changes. A sorted MultiIndex makes partial .loc[] slicing reliable; an unsorted MultiIndex can raise an UnsortedIndexError when you try to slice by a level. If you frequently use level-based lookups, call sort_index() once after building the MultiIndex.
Memory is also affected by index dtype. A MultiIndex of string labels uses more memory than a RangeIndex, but it can avoid keeping the same key as separate columns when you use drop=True. There is no universal rule; measure with df.memory_usage(deep=True) for large datasets.
One practical point: reset_index() followed by set_index() on the same columns is wasteful. If you only need to reorder levels, use swaplevel() or reorder_levels() instead.
Common mistakes and edge cases
Forgetting that the index has a name. When you reset_index() an unnamed index, the new column is called index. This is easy to miss in code that later references columns by name. Name the index explicitly with df.index.name = "id" or use rename_axis().
Duplicate index labels. set_index() does not check for duplicates by default. If the new index has repeated labels, .loc[] returns multiple rows and merges can produce unexpected row multiplication. Use verify_integrity=True when duplicates are invalid for your use case.
Mixing up level positions. reset_index(level=0) resets the outermost level. Level positions are zero-based from the outside. If the MultiIndex is ["region", "month"], level 0 is region and level 1 is month.
Column name collisions. When reset_index() writes the index back as a column, it raises a ValueError if a column with the same name already exists. Rename the index or the conflicting column first.
inplace returns None. If you use inplace=True, the method modifies the DataFrame and returns None, so it is easy to accidentally overwrite the DataFrame with None by assigning the return value. Prefer assigning the result of set_index() or reset_index().
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.