为了账号安全,请及时绑定邮箱和手机立即绑定

整理大熊猫实验结果

整理大熊猫实验结果

蝴蝶刀刀 2021-11-02 13:54:53
我有以下输入数据。每一行都是一个实验的结果:  instance algo  profit  time        x    A      10   0.5        y    A      20   0.1        z    A      13   0.7        x    B      39   0.9        y    B      12   1.2        z    B      14   0.6我想生成下表:            A               B   instance    profit  time    profit  timex           10      0.5     39      0.9y           20      0.1     12      1.2z           13      0.7     14      0.6我曾尝试使用 pivot 和 pivot_table 但没有成功。有没有办法用熊猫来达到这个结果?
查看完整描述

2 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

首先melt获取'profit'和'time'在同一列中,然后使用pivot table具有多个列级别的a


(df.melt(id_vars=['instance', 'algo'])

.pivot_table(index='instance', columns=['algo', 'variable'], values='value'))

#algo          A           B     

#variable profit time profit time

#instance                        

#x          10.0  0.5   39.0  0.9

#y          20.0  0.1   12.0  1.2

#z          13.0  0.7   14.0  0.6


查看完整回答
反对 回复 2021-11-02
?
富国沪深

TA贡献1790条经验 获得超9个赞

set_index和unstack:


df.set_index(['instance', 'algo']).unstack().swaplevels(1, 0, axis=1)



         profit     time     

algo          A   B    A    B

instance                     

x            10  39  0.5  0.9

y            20  12  0.1  1.2

z            13  14  0.7  0.6

(df.set_index(['instance', 'algo'])

   .unstack()

   .swaplevel(1, 0, axis=1)

   .sort_index(axis=1))


algo          A           B     

         profit time profit time

instance                        

x            10  0.5     39  0.9

y            20  0.1     12  1.2

z            13  0.7     14  0.6

另一种选择是使用pivotand swaplevel:


(df.pivot('instance', 'algo', ['profit', 'time'])

   .swaplevel(1, 0, axis=1)

   .sort_index(axis=1))


algo          A           B     

         profit time profit time

instance                        

x          10.0  0.5   39.0  0.9

y          20.0  0.1   12.0  1.2

z          13.0  0.7   14.0  0.6


查看完整回答
反对 回复 2021-11-02
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信