代码之家  ›  专栏  ›  技术社区  ›  Shuvayan Das

在excel中使用数据透视时跨多行聚合[重复]

  •  1
  • Shuvayan Das  · 技术社区  · 8 年前

    我有以下数据:

    enter image description here

    因此,对于每个设备,Sep、Oct和Nov的10个通道上都有小时数数据,这些数据需要在以device\u id为轴心的同时求和,从而得到输出 将如图的第二部分所示。

    以下是文本格式的数据:

    device_id   month_id channel    hours       brand
    214 201711  A           2.311       S
    214 201710  A           6.071       S
    214 201709  A           0.55        S
    214 201711  B           0.603       S
    214 201710  B           2.185       S
    214 201709  B           2.62        S
    214 201711  C           0.82        S
    214 201710  C           25.70       S
    214 201709  C           17.73       S
    
    Output:             
    device_id   A       B           C           brand
    214     8.933054    5.412499    44.261665   S
    

    所有数据都在pandas数据框中,我想使用pivot。有人能帮我吗?

    2 回复  |  直到 8 年前
        1
  •  1
  •   cs95    8 年前

    看起来你想要一个 pivot_table 操作-

    df = df.pivot_table(index=['device_id', 'brand'], 
                        columns='channel', 
                        values='hours', 
                        aggfunc=sum)\
           .reset_index()
    
    df.columns.name = None
    df
    
       device_id brand      A      B      C
    0        214     S  8.932  5.408  44.25
    
        2
  •  1
  •   Alexey Trofimov    8 年前

    一个衬里:

    df.groupby(["device_id", "brand", "channel"])["hours"].sum().unstack()
    

    其中给出:

    channel              A      B      C
    device_id brand                     
    214       S      8.932  5.408  44.25