我正在寻找pandas agg中的一种方法来查找列的值,基于其他列值。
例如: 我有以下数据框
df = pd.DataFrame({"Project":['A','B','C','D','E'],
"Country" :['Brazil','Brazil','Germany','Germany','Argentina'],\
"Value":[12,11,14,15,18]})
Country Project Value
0 Brazil A 12
1 Brazil B 11
2 Germany C 14
3 Germany D 15
4 Argentina E 18
我创建了这个聚合:
aggregations = {'Project':{'Number of projects':'count'},
'Value':{'Mean':'mean',
'Max':'max',
'Min':'min'}}
df.groupby(['Country']).agg(aggregations)
我想在这个聚合中添加一个新列,它将给出最大的项目名称 观察到'价值'。打算结果如下:
Project Value
Number of Projects Mean Max Min Projec_Max Projec_Min
Country
Argentina 1 18.0 18 18 E E
Brazil 2 11.5 12 11 A B
Germany 2 14.5 15 14 D C
如何在聚合字典中填写此内容?
提前致谢
答案 0 :(得分:0)
不确定这是否是最佳方式,但似乎有效:
aggregations = {'Project':{'Number of projects':'count'},
'Value':{'Mean':'mean',
'Max':'max',
'Min':'min',
'Project_Max': lambda x: df['Project'][x.idxmax()],
'Project_Min': lambda x: df['Project'][x.idxmin()]}}
df.groupby(['Country']).agg(aggregations)
结果:
Value Project
Project_Max Project_Min Max Mean Min Number of projects
Country
Argentina E E 18 18.0 18 1
Brazil A B 12 11.5 11 2
Germany D C 15 14.5 14 2