+

Python | Pandas DataFrame.reset_index ()

Pandas reset_index() — it is a method to reset the index of a data frame. The .reset_index () method sets a list of integers ranging from 0 to the length of the data as the index.

Syntax:
DataFrame..reset_index (level = None, drop = False, inplace = False, col_level = 0, col_fill = ”)

Parameters:
level: int, string or a list to select and remove passed column from index.
drop: Boolean value, Adds the replaced index column to the data if False.
inplace: Boolean value, make changes in the original data frame itself if True.
col_level: Select in which column level to insert the labels.
col_fill: Object, to determine how the other levels are named.

Return type: DataFrame

To load the CSV file you are using, press here.

Example # 1: Resetting the index
In this example, to reset the index, the Name column was first set as the column index, and then a new index was created using the reset index.

# import pandas package

import pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# set name as index column

data.set_index ([ "First Name" ], inplace = True ,

  append = True , drop = True )

 
# reset index

data. .reset_index (inplace = True )

 
# display
data.head ( )

Output:
As shown in the output images, a new index mark was created called level_0.

Before reset —

After reset —

Example # 2: Working with a multilevel index
In this example, 2 columns (Name and Gender) are added to the index column and then one level is removed using the .reset_index () method.

# import pandas package

import pandas as pd

 
# create data frame from CSV file

data = pd.read_csv ( "employees.csv" )

 
# set name as index column

data.set_index ([ "First Name" , "Gender" ], inplace = True ,

  append = True , drop = True )

  
# reset index

data..reset_index (level = 2 , inplace = True , col_level = 1 )

 
# display
d ata.head ()

Output:
As shown in the output image, the floor column in the index column was replaced because its level was 2.

Before reset —

After reset —

Get Solution for free from DataCamp guru