繁体   English   中英

使用密钥对的 Pivot/inverse Pandas Dataframe

[英]Pivot/inverse Pandas Dataframe using key pairs

我有这个我想翻转的数据框

        M1       M2      M3
John    0.10     0.74    0.25
Alex    0.80     0.15    0.05

我想将其转换为这种格式:

        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 

如果有有效的方法来做到这一点?

根据评论,阅读有关pd.melt的更多信息,您会喜欢在旋转数据框时使用它。

当您在旋转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