Reputation:
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
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