How to Reset an Index in Pandas DataFrame

To reset an index in Pandas DataFrame:

df.reset_index(drop=True, inplace=True)

Steps to Reset an Index in Pandas DataFrame

Step 1: Gather your data

For illustration purposes, let’s gather the following data about different products:

ProductPrice
Tablet250
Printer150
Laptop1200
Monitor300
Computer1500

Step 2: Create a DataFrame

Next, create a DataFrame to capture the above data in Python:

import pandas as pd

data = {'Product': ['Tablet', 'Printer', 'Laptop', 'Monitor', 'Computer'], 
        'Price': [250, 150, 1200, 300, 1500]
        }

df = pd.DataFrame(data)

print(df)

When you run the code in Python, you’ll get the following DataFrame:

    Product  Price
0    Tablet    250
1   Printer    150
2    Laptop   1200
3   Monitor    300
4  Computer   1500

Notice that the index values (highlighted in yellow) are sequential from 0 to 4.

Step 3: Drop Rows from the DataFrame

Before you reset the index in the DataFrame, let’s create a scenario where the index will no longer be sequential.

One way to do that is by dropping some of the rows in the DataFrame. For example, let’s drop the first row (index of 0), as well as the fourth row (index of 3):

df.drop([0, 3], inplace=True)

So the full code would look like this:

import pandas as pd

data = {'Product': ['Tablet', 'Printer', 'Laptop', 'Monitor', 'Computer'], 
        'Price': [250, 150, 1200, 300, 1500]
        }

df = pd.DataFrame(data)

df.drop([0, 3], inplace=True)

print(df)

You’ll now notice that the index is no longer sequential:

    Product  Price
1   Printer    150
2    Laptop   1200
4  Computer   1500

Step 4: Reset the Index in Pandas DataFrame

To reset the index in the DataFrame you’ll need to apply the following syntax:

df.reset_index(drop=True, inplace=True)

Putting everything together:

import pandas as pd

data = {'Product': ['Tablet', 'Printer', 'Laptop', 'Monitor', 'Computer'], 
        'Price': [250, 150, 1200, 300, 1500]
        }

df = pd.DataFrame(data)

df.drop([0, 3], inplace=True)

df.reset_index(drop=True, inplace=True)

print(df)

You’ll now get a sequential index that starts from 0:

    Product  Price
0   Printer    150
1    Laptop   1200
2  Computer   1500

Leave a Comment