代码之家  ›  专栏  ›  技术社区  ›  Mark Pedigo

Python在数据帧内聚合系列数据

  •  1
  • Mark Pedigo  · 技术社区  · 7 年前

    在一个数据帧中,我尝试将split-apply-combine应用于包含序列数据元素的列。(我已经搜索过了,但在数据帧中没有找到任何与序列相关的内容。)

    数据帧:

    import pandas as pd
    from pandas import Series, DataFrame
    
    import numpy as np
    
    ex = {'account': [1, 1, 1, 2, 2],
          'subaccount': [1, 2, 3, 1, 2],
          'account_type':  ['A', 'A', 'B', 'A', 'B'],
          'data': [(1, 2, 3), (4, 5, 6), (7, 8, 9), (1, 3, 5), (2, 4, 6)]}
    
    df = DataFrame(ex, columns=['account', 'subaccount', 'account_type', 'data'])
    

    result = (df.groupby(['account', 'account_type'])
               .agg({'subaccount': np.sum}))
    

    这让我

                           subaccount
    account  account_type
    1        A             3
             B             3
    2        A             1
             B             2
    

    但我想要的是

                          subaccount
    account  account_type
    1        A            (5, 7, 9)
             B            (7, 8, 9)
    2        A            (1, 3, 5)
             B            (2, 4, 6)
    

    我可能错过了一些显而易见的东西,但我没有找到解决办法。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Alexander    7 年前
    >>> df.groupby(['account', 'account_type']).apply(
            lambda group: tuple(group['data'].apply(pd.Series).sum()))
    account  account_type
    1        A               (5, 7, 9)
             B               (7, 8, 9)
    2        A               (1, 3, 5)
             B               (2, 4, 6)
    dtype: object
    
        2
  •  1
  •   Phik    7 年前

    result = df.groupby(['account', 'account_type'])\
           .apply(lambda x : [sum(y) for y in zip(*x["data"])])