首页 > 解决方案 > 根据python中的自定义函数聚合数据框中的每一列

问题描述

这是我的数据框:

df = [{'id': 1, 'name': 'bob', 'apple': 45, 'grape': 10, 'rate':0}, 
      {'id': 1, 'name': 'bob', 'apple': 45, 'grape': 20, 'rate':0},
      {'id': 2, 'name': 'smith', 'apple': 5, 'grape': 30, 'rate':0},
      {'id': 2, 'name': 'smith', 'apple': 10, 'grape': 40, 'rate':0}]

我想:其中apple=apple.sum() 和grape=grape.sum() 和rate=grape/apple*100。

       id           name     apple    grape   rate
0       1            bob      90       30      300 
1       2           smith     15       70      21.4

我尝试了以下方法:

df = pd.DataFrame(df)
def cal_rate(rate):
    return df['apple'] / df['grape']*100
agg_funcs = {'apple':'sum',
             'grape':'sum',
             'rate' : cal_rate}
df=df.groupby(['id','name').agg(agg_funcs).reset_index()

但是得到了这个结果:

       id           name     apple    grape   rate
0       1            bob      90       30      105 
1       2           smith     15       70      105

你能帮我吗?在此先感谢。

标签: pythonpandasdataframeaggregate

解决方案


干得好:

import pandas as pd

df = [{'id': 1, 'name': 'bob', 'apple': 45, 'grape': 10, 'rate':0},
      {'id': 1, 'name': 'bob', 'apple': 45, 'grape': 20, 'rate':0},
      {'id': 2, 'name': 'smith', 'apple': 5, 'grape': 30, 'rate':0},
      {'id': 2, 'name': 'smith', 'apple': 10, 'grape': 40, 'rate':0}]
df = pd.DataFrame(df)


def cal_rate(group):
    frame = df.loc[group.index]
    return frame['apple'].sum()  / frame['grape'].sum() * 100
agg_funcs = {'apple':'sum',
             'grape':'sum',
             'rate' : cal_rate}
df=df.groupby(['id','name']).agg(agg_funcs).reset_index()
print(df)

输出

   id   name  apple  grape   rate
0   1    bob     90     30  300.0
1   2  smith     15     70   21.4

推荐阅读