python - 根据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
你能帮我吗?在此先感谢。
解决方案
干得好:
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
推荐阅读
- javascript - 使用 Sequelize 在数据库中创建新列?
- ms-access-2007 - Access 2007 不会打开 accdb 文件,除非它被重命名
- r - 根据第一次出现更改组中的值
- javascript - 构建 Web 应用程序时如何绕过客户端的 cors 错误?
- odata - 将标头添加到有效负载中的单个调用
- csv - 使用 vbs 删除 .csv 中具有空列的行
- apache-kafka - Kafka 机架感知设置
- javascript - 是否可以在不将 jitsi 托管在私人服务器上的情况下更改 Jitsi 共享 URL?
- php - php基于时间的图像不会改变
- amazon-cloudformation - 如何在创建 CodePipeline 之前在 CloudFormation 中创建 ECS 任务