How can I transform a DataFrame so that the headers become column values?

Viewed 51

I have Pandas DataFrame in this form:

Data Format 1

How can I transform this into a new DataFrame with this form:

Data Format 2

I am beginning to use Seaborn and Plotly for plotting, and it seems like they prefer data to be formatted in the second way.

3 Answers

Lets try set_index(), unstack(), renamecolumns

`df.set_index('Date').unstack().reset_index().rename(columns={'level_0':'Name',0:'Score'})`

How it works

df.set_index('Date')#Sets Date as index
df.set_index('Date').unstack()#Flips, melts the dataframe
d=df.set_index('Date').unstack().reset_index()# resets the datframe and allocates columns, those in index become level_suffix and attained values become 0
d.rename(columns={'level_0':'Name',0:'Score'})#renames columns

Use melt function in pandas

df.melt(id_vars="Date", value_vars=["Andy", "Barry", "Cathy"], var_name="Name", value_name="Score")

This should work :

df.stack().reset_index(level=1).rename(columns={'level_1':'Name')
Related