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:
Syntax
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
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
- Losing the old index by using drop=True
- Forgetting both return new DataFrames
- 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: