How to used pandas.assign to create a new column from the pandas DataFrame index

Question:

I am trying to use the pandas assign method to create a new column which derives its values from the Dataframe index. I really want to use the assign function to achieve the desired output. How do I do this? Thanks in advance.

import pandas as pd
df = pd.DataFrame([1,2,3,4,5],index=['A','B','C','D','E'],columns= 
     ['Score'])
df  

df.assign(Person=df.index)
df

Actual Output

enter image description here

Desired Output

enter image description here

Asked By: AnalysisNerd

||

Answers:

is this what you are looking for?

1 first way not using assign:

import pandas as pd
import numpy as np

df = pd.DataFrame([1,2,3,4,5],index=['A','B','C','D','E'],columns= 
     ['Score'])

df=df.reset_index().rename(columns={'index': 'Person'})
df

2 second way using assign:

df = pd.DataFrame([1,2,3,4,5],index=['A','B','C','D','E'],columns= 
 ['Score'])


df=df.assign(Person=df.index).reset_index()

df=df.drop(['index'], axis=1)
df
Answered By: Jessica
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.