使用groupby对Pandas DataFrame进行计算,然后将其传递回DataFrame?

时间:2016-07-25 19:09:02

标签: python pandas dataframe grouping

我有一个数据框,我想用两个变量分组,然后在这些变量中执行计算。是否有任何简单的方法可以做到这一点,并在完成后将信息返回到DataFrame中,例如:

df=pd.DataFrame({'A':[1,1,1,2,2,2,30,12,122,345],
'B':[1,1,1,2,3,3,3,2,3,4],
'C':[101,230,12,122,345,23,943,83,923,10]})

total = []
avg = []
AID = []
BID = []
for name, group in df.groupby(['A', 'B']):
    total.append(group.C.sum())
    avg.append(group.C.sum()/group.C.nunique())
    AID.append(name[0])
    BID.append(name[1])

x = pd.DataFrame({'total':total,'avg':avg,'AID':AID,'BID':BID})

但显然效率更高?

1 个答案:

答案 0 :(得分:2)

您可以在pandas之后使用groupby汇总功能:

import pandas as pd
import numpy as np
df.groupby(['A', 'B'])['C'].agg({'total': np.sum, 'avg': np.mean}).reset_index()

#      A    B   total          avg
# 0    1    1     343   114.333333
# 1    2    2     122   122.000000
# 2    2    3     368   184.000000
# 3   12    2      83    83.000000
# 4   30    3     943   943.000000
# 5  122    3     923   923.000000
# 6  345    4      10    10.000000