AnalysisNerd
AnalysisNerd

Reputation: 133

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

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

Upvotes: 0

Views: 1570

Answers (1)

Jessica
Jessica

Reputation: 3173

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

Upvotes: 1

Related Questions