我正在 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
我如何在聚合字典中实现这个?
提前致谢
不确定这是否是最好的方法,但它似乎有效:
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