Add Indices of pandas DataFrame as New Column in Python (Example Code)

In this tutorial you’ll learn how to append the index of a pandas DataFrame as new variable in the Python programming language.

Setting up the Example

import pandas as pd                            # Load pandas library
my_df = pd.DataFrame({'A':[1, 1, 1, 1, 1],    # Construct example DataFrame
                      'B':[2, 2, 2, 2, 2],
                      'C':[3, 3, 3, 3, 3]})
print(my_df)                                  # Display example DataFrame in console
#    A  B  C
# 0  1  2  3
# 1  1  2  3
# 2  1  2  3
# 3  1  2  3
# 4  1  2  3

Example: Converting Indices to Column Using index Attribute

my_df['ind'] = my_df.index                    # Index as variable
print(my_df)                                  # Display DataFrame once again
#    A  B  C  ind
# 0  1  2  3    0
# 1  1  2  3    1
# 2  1  2  3    2
# 3  1  2  3    3
# 4  1  2  3    4

Leave a Reply

Your email address will not be published.

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