How to Reset an Index in Python?

Estimated read time 2 min read

To reset an index in Python, you can use the reset_index() method available in pandas, a popular data manipulation library. This method resets the index of a DataFrame or a Series, providing a new default numerical index.

Here’s an example of how to reset an index using the reset_index() method:

import pandas as pd

# Create a DataFrame
data = {'Name': ['John', 'Emma', 'Peter', 'Olivia'],
        'Age': [25, 28, 30, 27]}
df = pd.DataFrame(data)

# Set 'Name' column as the index
df.set_index('Name', inplace=True)

# Print the DataFrame with the modified index


John     25
Emma     28
Peter    30
Olivia   27

The DataFrame df has the ‘Name’ column set as the index. To reset the index, you can call the reset_index() method:

# Reset the index
df_reset = df.reset_index()

# Print the DataFrame with the reset index


     Name  Age
0    John   25
1    Emma   28
2   Peter   30
3  Olivia   27

In the code above, the reset_index() method is called on the DataFrame df, and the result is assigned to a new DataFrame called df_reset. The new DataFrame df_reset has a default numerical index, and the original index becomes a regular column named ‘Name’.

Note that the reset_index() method does not modify the original DataFrame but returns a new DataFrame with the reset index. If you want to modify the DataFrame in-place, you can pass the inplace=True parameter to the reset_index() method like this: df.reset_index(inplace=True).

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply