Python在数据帧内聚合系列数据
在dataframe中,我尝试将split apply combine应用于包含序列数据元素的列。(我已经搜索了这么多,但在数据帧中没有找到任何与系列相关的内容。) 数据帧:Python在数据帧内聚合系列数据,python,pandas,split-apply-combine,Python,Pandas,Split Apply Combine,在dataframe中,我尝试将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], 'accoun
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)
我可能遗漏了一些显而易见的东西,但解决方案却让我不知所措。这很有效
result = df.groupby(['account', 'account_type'])\
.apply(lambda x : [sum(y) for y in zip(*x["data"])])
但是,对于大数据集来说,它可能会很慢,因为它是一个小数据集,所以工作正常。多谢!
>>> 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