Examples
import numpy as np
import pandas as pd
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
When we reset the index, the old index is added as a column, and a new sequential index is used:
df.reset_index()
Use the drop parameter to avoid the old index being added as a column:
df.reset_index(drop=True)
You can also use reset_index with MultiIndex.
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')])
df = pd.DataFrame([(360.0, 'fly'),
( 30.0, 'fly'),
( 80.5, 'run'),
(np.nan, 'jump')],
index=index,
columns=columns)
df
If the index has multiple levels, we can reset a subset of them:
df.reset_index(level='class')
If we are not dropping the index, by default, it is placed in the top level.
We can place it in another level:
df.reset_index(level='class', col_level=1)
When the index is inserted under another level, we can specify under
which one with the parameter col_fill:
df.reset_index(level='class', col_level=1, col_fill='species')
If you specify a nonexistent level for col_fill, it is created:
df.reset_index(level='class', col_level=1, col_fill='genus')