Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to reset index in Pandas dataframe?



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.

Algorithm

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)

Output

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: 2021-03-16T10:14:44+05:30

401 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements