2017-09-06 71 views
1

在一個數據框中,我嘗試將split-apply-combine與包含系列數據元素的列進行拆分。 (我已經搜查SO但沒有發現有關的數據幀中的一系列事情。)Python Pandas在DataFrame中彙總系列數據

數據幀:

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']) 

然後我GROUPBY和聚合,就像這樣。

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) 

我可能失去了一些東西很明顯,但解決的辦法逃脫我。

回答

1

這工作

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

但是它可能是一個大的數據集

+0

這是一個小的數據集緩慢,使作品就好了。非常感謝! –

2
>>> 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