【问题标题】:Python Pandas Aggregate Series Data Within a DataFramePython Pandas 在 DataFrame 中聚合系列数据
【发布时间】:2017-09-06 20:26:55
【问题描述】:

在数据框中,我尝试将拆分应用组合到包含系列数据元素的列。 (我已经搜索过 SO,但没有找到与数据框中的系列有关的任何内容。)

数据框:

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)

我可能遗漏了一些明显的东西,但解决方案让我无法理解。

【问题讨论】:

    标签: python pandas split-apply-combine


    【解决方案1】:
    >>> 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】:

      这行得通

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

      但是对于大型数据集可能会很慢

      【讨论】:

      • 这是一个小数据集,所以工作得很好。非常感谢!
      猜你喜欢
      • 2021-04-14
      • 2018-08-21
      • 1970-01-01
      • 2021-04-06
      • 2021-04-06
      • 2021-04-14
      • 1970-01-01
      • 2012-06-12
      相关资源
      最近更新 更多