0

I'm relatively new to pandas and I am stuck on how to restructure a dataframe. Here is a very simplified example of what I want to do:

My current df is:

Name Company 20210102        
John X       Y    

and I want to transform it to:

Date      Name Company Paycheck

20210102  John X       Y

I feel like I should be using pivot_table somehow but not sure how.. any help is appreciated

1 Answer 1

1

Setting up the data will give you

data = { 'Name' : ['John'], 'Company' : ['X'], '20210102' : ['Y'] }
df = pd.DataFrame(data)
print(df)

and this data

   Name Company 20210102
0  John       X        Y

now using melt

print( pd.melt(df, id_vars=['Name','Company'], var_name='20210102'))

will give you

   Name Company  20210102 value
0  John       X  20210102     Y

so finally

df2 = pd.melt(df, id_vars=['Name','Company'], var_name='20210102')
df2.columns = ['Name','Company','Date','Paycheck']
print(df2)

Yields

   Name Company      Date Paycheck
0  John       X  20210102        Y

Not sure if this is what you wanted...

Sign up to request clarification or add additional context in comments.

2 Comments

You seem to misunderstand what var_name means. Passing var_name='Date', value_name='Paycheck' to melt saves you the rename df.columns=...
Thank you both Paul and Quang.. very helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.