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. Here is an example:
import pandas as pd
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=[100, 101, 102])
# Convert index to column
df.reset_index(inplace=True, name='Index_Column')
print(df)
Watch a video course
Python - The Practical Guide
This will output:
Index_Column A B 0 100 1 4 1 101 2 5 2 102 2 6
Note that name
parameter specify the column name of new index.