Change Index Name of pandas DataFrame in Python (Example Code)

In this Python tutorial you’ll learn how to change the indices of a pandas DataFrame.

Constructing Example Data

import pandas as pd                                # Load pandas
my_df = pd.DataFrame({'A':[1, 2, 9, 5, 1, 2, 5],  # Construct example DataFrame in Python
                      'B':[5, 6, 6, 7, 1, 9, 2],
                      'C':[8, 2, 5, 6, 8, 2, 1],
                      'D':['a', 'b', 'c', 'd', 'e', 'f', 'g']})
print(my_df)                                      # Display example DataFrame in console
#    A  B  C  D
# 0  1  5  8  a
# 1  2  6  2  b
# 2  9  6  5  c
# 3  5  7  6  d
# 4  1  1  8  e
# 5  2  9  2  f
# 6  5  2  1  g

Example: Use Variable of pandas DataFrame as Indices

my_df_new = my_df.set_index('D')                  # Column as index
print(my_df_new)                                  # Display new pandas DataFrame
#    A  B  C
# D         
# a  1  5  8
# b  2  6  2
# c  9  6  5
# d  5  7  6
# e  1  1  8
# f  2  9  2
# g  5  2  1

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