2017-09-06 6 views
1

Innerhalb eines Datenrahmens versuche ich Split-Apply-Combine zu einer Spalte, die seriell Datenelement enthält. (Ich habe SO gesucht, aber nichts in Bezug auf Serie innerhalb von Datenrahmen gefunden.)Python Pandas Aggregatserien Daten innerhalb eines Datenrahmens

Der Datenrahmen:

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

Dann habe ich GROUPBY und Aggregat, wie so.

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

Das gibt mir

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

aber was ich will, ist

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

ich wohl offensichtlich etwas fehlt bin, aber die Lösung entgeht mir.

Antwort

1

Dies funktioniert

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

aber es für eine große Datenmenge langsam sein kann

+0

Es ist eine kleine Datenmenge, so dass nur gut funktioniert. Vielen Dank! –

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 
Verwandte Themen