简体   繁体   English

使用密钥对的 Pivot/inverse Pandas Dataframe

[英]Pivot/inverse Pandas Dataframe using key pairs

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.根据评论,阅读有关pd.melt的更多信息,您会喜欢在旋转数据框时使用它。

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 .当您在旋转M的三列时保留索引时,您可以先执行pd.melt ,然后执行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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM