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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.