How to reset index in Pandas dataframe?

PythonPandasServer Side ProgrammingProgramming

In this program, we will replace or, in other words, reset the default index in the Pandas dataframe. We will first make a dataframe and see the default index and then replace this default index with our custom index.


Step 1: Define your dataframe.
Step 2: Define your own index.
Step 3: Replace the default index with your index using the reset function in Pandas library.

Example Code

import pandas as pd

dataframe = {'Name':["Allen", "Jack", "Mark", "Vishal"],'Marks':[85,92,99,87]}

df = pd.DataFrame(dataframe)
print("Before using reset_index:\n", df)

own_index = ['a', 'j', 'm', 'v']

df = pd.DataFrame(dataframe, own_index)
df.reset_index(inplace = True)

print("After using reset_index:\n", df)


Before using reset_index():
     Name  Marks
0   Allen     85
1    Jack     92
2    Mark     99
3  Vishal     87

After using reset_index():
   index    Name  Marks
0      0   Allen     85
1      1    Jack     92
2      2    Mark     99
3      3  Vishal     87
Updated on 16-Mar-2021 10:14:44