How to Convert Index to Column in Pandas DataFrame?

In this tutorial, we will learn how to convert index to column in Pandas DataFrame with the help of example? By Pranit Sharma Last updated : April 12, 2023

Overview

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. In a DataFrame, each row is assigned with an index value ranging from 0 to n-1. The 0th is the first row and n-1th index is the last row. Pandas provides us the simplest way to convert the index into a column.

Convert Index to Column in Pandas Dataframe

To convert index to column in Pandas DataFrame, create a new column and assign the index value of each row using DataFrame.index property. It returns a list of all the index values which are assigned with each row.

Syntax

DataFrame.index

Example to convert index to column in Pandas DataFrame

# Importing pandas package
import pandas as pd

# Creating a dictionary of student marks
d = {
    "Peter":[65,70,70,75],
    "Harry":[45,56,66,66],
    "Tom":[67,87,65,53],
    "John":[56,78,65,64]
}

# Now, create DataFrame and assign index name 
# as subject names
df = pd.DataFrame(d,index=["Maths","Physics","Chemistry","English"])

# Printing the DataFrame
print("\noriginal DataFrame\n\n",df,"\n\n")

# Create a new column and insert its values 
# using DataFrame.index
df['index'] = df.index

# Printing new DataFrame
print("\nNew DataFrame\n\n",df)

Output


original DataFrame

            Peter  Harry  Tom  John
Maths         65     45   67    56
Physics       70     56   87    78
Chemistry     70     66   65    65
English       75     66   53    64 



New DataFrame

            Peter  Harry  Tom  John      index
Maths         65     45   67    56      Maths
Physics       70     56   87    78    Physics
Chemistry     70     66   65    65  Chemistry
English       75     66   53    64    English

Output (Screenshot)

Convert Index to Column | Output

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.