user9628064
user9628064

Reputation:

How can I restructure a dataframe in pandas?

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

Upvotes: 0

Views: 37

Answers (1)

Paul Brennan
Paul Brennan

Reputation: 2696

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...

Upvotes: 1

Related Questions