猿问

整理大熊猫实验结果

我有以下输入数据。每一行都是一个实验的结果:


  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  time

x           10      0.5     39      0.9

y           20      0.1     12      1.2

z           13      0.7     14      0.6

我曾尝试使用 pivot 和 pivot_table 但没有成功。有没有办法用熊猫来达到这个结果?


蝴蝶刀刀
浏览 170回答 2
2回答

BIG阳

首先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

富国沪深

set_index和unstack:df.set_index(['instance', 'algo']).unstack().swaplevels(1, 0, axis=1)         profit     time     algo          A   B    A    Binstance                     x            10  39  0.5  0.9y            20  12  0.1  1.2z            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 timeinstance                        x            10  0.5     39  0.9y            20  0.1     12  1.2z            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 timeinstance                        x          10.0  0.5   39.0  0.9y          20.0  0.1   12.0  1.2z          13.0  0.7   14.0  0.6
随时随地看视频慕课网APP

相关分类

Python
我要回答