W3docs

How to convert index of a pandas dataframe into a column

To convert the index of a pandas DataFrame into a column, you can use the reset_index() function, and specify that you want to move the index to a new column with the inplace=True and name parameter.

To convert the index of a pandas DataFrame into a column, you can use the reset_index() function. First, set the index name using df.index.name = 'Column_Name', then call reset_index(). Here is an example:

Convert index of a pandas dataframe into a column

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=[100, 101, 102])

# Set index name and convert to column
df.index.name = 'Index_Column'
df.reset_index(inplace=True)

print(df)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This will output:


Index_Column  A  B
0           100  1  4
1           101  2  5
2           102  3  6

Note that setting df.index.name specifies the column name for the converted index.