代码之家  ›  专栏  ›  技术社区  ›  user3486773

熊猫支点?透视表?融化?堆叠还是取消堆叠?

  •  1
  • user3486773  · 技术社区  · 4 年前

           id    Revenue  Cost  qty  time
      0    A      400       50    2     1
      1    A      900      200    8     2
      2    A      800      100    8     3
      3    B      300       20    1     1
      4    B      600      150    4     2
      5    B      650      155    4     3
    

    我正努力做到这一点:

           id    Type       1      2      3     
      0    A    Revenue    400    900    800
      1    A    Cost        50    200    100     
      2    A    qty          2      8      8   
      3    B    Revenue    300    600    650
      4    B    Cost        20    150    155
      5    B    qty          1      4      4
    

    其中时间总是重复1-3,所以我需要把时间调换或旋转,列为1-3

      pd.pivot_table(df, values = ['Revenue', 'qty', 'Cost'] , index=['id'], columns='time').reset_index()
    

       Revenue                   qty                Cost
           1     2     3         1     2     3         1    2     3
    

    在这种情况下,我需要将Revenue、qty和Cost转换为一行,只使用1、2、3作为列名。因此,每个“类型”的ID都是重复的,但要根据时间1-3列出。

    1 回复  |  直到 4 年前
        1
  •  0
  •   BENY    4 年前

    我们还是可以的 unstack stack

    df.set_index(['id','time']).stack().unstack(level=1).reset_index()
    Out[24]: 
    time id  level_1    1    2    3
    0     A  Revenue  400  900  800
    1     A     Cost   50  200  100
    2     A      qty    2    8    8
    3     B  Revenue  300  600  650
    4     B     Cost   20  150  155
    5     B      qty    1    4    4