-1

I have this dataframe that I would like to flip

        M1       M2      M3
John    0.10     0.74    0.25
Alex    0.80     0.15    0.05

I would like to convert it to this format:

        M        value    
John    M1       0.10   
John    M2       0.74
John    M3       0.25 
Alex    M1       0.80   
Alex    M2       0.15
Alex    M3       0.05 

If there an efficient way to do this?

1 Answers1

0

Based on the comment, read more about pd.melt and you will love to use it when you are pivoting the dataframe.

As you are keeping the index while pivoting the three columns of M, you can do a pd.melt first and then do sort_index.

df.melt(value_vars = df.columns, var_name='M', ignore_index=False).sort_index(ascending=False)
Out[62]: 
       M  value
John  M1   0.10
John  M2   0.74
John  M3   0.25
Alex  M1   0.80
Alex  M2   0.15
Alex  M3   0.05