gpt4 book ai didi

python - 特定格式的数据框枢轴

转载 作者:太空宇宙 更新时间:2023-11-04 04:01:29 26 4
gpt4 key购买 nike

目前我有以下格式的数据框:

ID  Value   Type    Month
1 0.1 B Jan
2 0.2 A Jan
1 0.15 A Feb
2 0.1 B Feb

我试图让它像这样按月显示每个列值:

Month Jan            Feb
Value Type Value Type
ID
1 0.1 B 0.15 A
2 0.2 A 0.1 B

我运行以下命令来透视数据

df.pivot(index='ID', columns='Month', values=['Type', 'Value'])

但是表格是这样出来的

      Value        Type
Jan Feb Jan Feb
ID
1 0.1 0.15 B A
2 0.2 0.1 A B

有什么办法让它像我想要的那样出来吗?一直无法找到一种方法来构建数据透视表,就像我想要的那样。 How to pivot a dataframe似乎没有解决这个特定的格式请求

最佳答案

使用swaplevelsort_index从你上次旋转的 df 开始。

df2.swaplevel(axis=1).sort_index(axis=1, ascending=[False, False])

Month   Jan        Feb     
Value Type Value Type
ID
1 0.1 B 0.15 A
2 0.2 A 0.1 B

关于python - 特定格式的数据框枢轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238125/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com