Skip to content
Justice Tech School

Set and Reset the Index

set_index makes a column the row label and reset_index turns it back into a normal column.

Example
import pandas as pd
import numpy as np
df = pd.DataFrame({'name': ['Ada', 'Bob', 'Cy', 'Di'], 'age': [30, 25, 35, 28], 'city': ['Lagos', 'Accra', 'Lagos', 'Nairobi'], 'score': [88.5, 92.0, 79.5, 85.0]})
x = df.set_index('name')
print(x.loc['Bob', 'age'])
print(x.head(2))
print(x.reset_index().columns.tolist())

Result

25
      age   city  score
name                   
Ada    30  Lagos   88.5
Bob    25  Accra   92.0
['name', 'age', 'city', 'score']

Exercise

Use name as index.

df.set_index("")

Quiz Test

What does reset_index do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.