Reset & Reindex pandas DataFrame in Python (2 Examples)

This tutorial illustrates how to reset and change the index of a pandas DataFrame in Python.

Preparing the Examples

import pandas as pd                                 # Load pandas library
my_df = pd.DataFrame({'A':range(10, 17),            # Construct pandas DataFrame
                      'B':range(7, 0, - 1)},
                     index = [50, 1, 8, 99, 20, 13, 7])
print(my_df)
#      A  B
# 50  10  7
# 1   11  6
# 8   12  5
# 99  13  4
# 20  14  3
# 13  15  2
# 7   16  1

Example 1: Applying reset_index() Function to Reset pandas DataFrame Index

df_new1 = my_df.reset_index(drop = True)            # Resetting index
print(df_new1)
#     A  B
# 0  10  7
# 1  11  6
# 2  12  5
# 3  13  4
# 4  14  3
# 5  15  2
# 6  16  1

Example 2: Applying reindex() Function to Reindex pandas DataFrame

df_new2 = my_df.reindex([8, 50, 1, 20, 13, 99, 7])  # Reindexing index
print(df_new2)
#      A  B
# 8   12  5
# 50  10  7
# 1   11  6
# 20  14  3
# 13  15  2
# 99  13  4
# 7   16  1

Related Articles & Further Resources

In addition, you could have a look at the related articles on this website. Some articles are listed below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top