Skip to content
Advertisement

Transpose both columns and the first row with pandas

Please help transposing this df. Can’t think of better way doing it:

df: Yellow marked are column names

enter image description here

outcome I’m looking for:

enter image description here

Advertisement

Answer

try via T attribute,rename_axis(),reset_index() and melt() method:

out=(df.T
     .rename_axis(index=['Group','Weeks'])
     .reset_index()
     .melt(['Group','Weeks'],var_name='Days',value_name='Amount'))

OR

via T attribute,rename_axis(),stack(),reset_index() and rename() method:

out=(df.T
   .rename_axis(index=['Group','Weeks'])
   .stack()
   .reset_index()
   .rename(columns={'level_2':'Days',0:'Amount'}))
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement