如何将groupby-apply-aggregate返回到Python Pandas中的数据帧?

时间:2017-02-10 14:32:19

标签: python pandas

def my_per_group_func(temp):

    # apply some tricks here
    return a, b, c, d

output =  dataframe.groupby('group_id').apply(my_per_group_func)

我的问题是如何聚合"输出"回到带有一些列名的数据帧(显然数据帧的索引是group_id)?

通常我所做的是使用聚合函数

但问题在于my_per_group_func在这里非常复杂,无法使用通常的'聚合'函数语法

有没有人有线索?

由于

2 个答案:

答案 0 :(得分:1)

似乎需要返回DataFrameSeries - 请检查flexible apply docs

dataframe = pd.DataFrame({'group_id':[1,1,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (dataframe)
   B  C  D  E  F  group_id
0  4  7  1  5  7         1
1  5  8  3  3  4         1
2  6  9  5  6  3         3

def my_per_group_func(x):
    #print (x)
    #some sample operations
    a = x.B + x.C
    b = x.E + x.B
    c = x.D + x.F
    d = x.F + x.E
    return pd.DataFrame({'group_id': x.group_id, 'a':a, 'b':b, 'c':c, 'd':d})

output =  dataframe.groupby('group_id').apply(my_per_group_func)
print (output)
    a   b  c   d  group_id
0  11   9  8  12         1
1  13   8  7   7         1
2  15  12  8   9         3
def my_per_group_func(x):
    #print (x)
    #some sample aggregations
    a = (x.B + x.C).mean()
    b = (x.E + x.B).sum()
    c = (x.D + x.F).median()
    d = (x.F + x.E).std()
    return pd.Series([a,b,c,d], index=['a','b','c','d'])

output =  dataframe.groupby('group_id').apply(my_per_group_func)
print (output)
             a     b    c         d
group_id                           
1         12.0  17.0  7.5  3.535534
3         15.0  12.0  8.0       NaN

答案 1 :(得分:0)

dataframe['new column name'] = dataframe.groupby('group_id').transform(my_per_group_func)