← Back to Pandas Course | Chapter 4: Indexing & Selection | Lesson 7 of 7

reset_index/set_index

set_index turns a column into the row labels and reset_index turns the labels back into a normal column.

In this page:

  1. reset_index/set_index
Syntax
python
df = df.set_index("column")
df = df.reset_index()

reset_index/set_index

set_index("col") makes a column the index, optionally dropping it from the columns. reset_index() moves the index back into a column and restores a 0..n-1 index; drop=True discards the old index instead. These two are the flip sides of the same coin.

Note: After filtering, reset_index(drop=True) gives a clean 0..n-1 index.

Example: reset_index/set_index

python
import pandas as pd

df = pd.DataFrame({"id": [101, 102, 103], "name": ["Ann", "Bob", "Cy"]})
by_id = df.set_index("id")
print(by_id)
print(by_id.loc[102, "name"])
print(by_id.reset_index())

# Output:
#     name
# id
# 101  Ann
# 102  Bob
# 103   Cy
# Bob
#     id name
# 0  101  Ann
# 1  102  Bob
# 2  103   Cy
Related Topics
Common Mistakes
  1. Losing the old index by using drop=True
  2. Forgetting both return new DataFrames
  3. Duplicate index values
Chapter Summary
  • set_index promotes a column to the index
  • reset_index demotes it
  • drop=True discards the old index
  • Both return new DataFrames
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.