Examples

In [1]:
import numpy as np
import pandas as pd
In [2]:
df = pd.DataFrame([('bird', 360.0),
                   ('bird', 30.0),
                   ('mammal', 96.5),
                   ('mammal', np.nan)],
                  index=['eagle', 'sparrow', 'tiger','Kangaroo'],
                  columns=('class', 'max_speed'))
df
Out[2]:
class max_speed
eagle bird 360.0
sparrow bird 30.0
tiger mammal 96.5
Kangaroo mammal NaN

When we reset the index, the old index is added as a column, and a new sequential index is used:

In [3]:
df.reset_index() 
Out[3]:
index class max_speed
0 eagle bird 360.0
1 sparrow bird 30.0
2 tiger mammal 96.5
3 Kangaroo mammal NaN

Use the drop parameter to avoid the old index being added as a column:

In [4]:
df.reset_index(drop=True)
Out[4]:
class max_speed
0 bird 360.0
1 bird 30.0
2 mammal 96.5
3 mammal NaN

You can also use reset_index with MultiIndex.

In [5]:
index = pd.MultiIndex.from_tuples([('bird', 'eagle'),
                                   ('bird', 'sparrow'),
                                   ('mammal','tiger'),
                                   ('mammal','Kangaroo')],
                                  names=['class', 'name'])
columns = pd.MultiIndex.from_tuples([('speed', 'max'),
                                     ('species', 'type')])
In [6]:
df = pd.DataFrame([(360.0, 'fly'),
                   ( 30.0, 'fly'),
                   ( 80.5, 'run'),
                   (np.nan, 'jump')],
                  index=index,
                  columns=columns)
df
Out[6]:
speed species
max type
class name
bird eagle 360.0 fly
sparrow 30.0 fly
mammal tiger 80.5 run
Kangaroo NaN jump

If the index has multiple levels, we can reset a subset of them:

In [7]:
df.reset_index(level='class')
Out[7]:
class speed species
max type
name
eagle bird 360.0 fly
sparrow bird 30.0 fly
tiger mammal 80.5 run
Kangaroo mammal NaN jump

If we are not dropping the index, by default, it is placed in the top level.
We can place it in another level:

In [8]:
df.reset_index(level='class', col_level=1)
Out[8]:
speed species
class max type
name
eagle bird 360.0 fly
sparrow bird 30.0 fly
tiger mammal 80.5 run
Kangaroo mammal NaN jump

When the index is inserted under another level, we can specify under
which one with the parameter col_fill:

In [9]:
df.reset_index(level='class', col_level=1, col_fill='species')
Out[9]:
species speed species
class max type
name
eagle bird 360.0 fly
sparrow bird 30.0 fly
tiger mammal 80.5 run
Kangaroo mammal NaN jump

If you specify a nonexistent level for col_fill, it is created:

In [10]:
df.reset_index(level='class', col_level=1, col_fill='genus')
Out[10]:
genus speed species
class max type
name
eagle bird 360.0 fly
sparrow bird 30.0 fly
tiger mammal 80.5 run
Kangaroo mammal NaN jump