使用 pandas 聚合基于其他列的结果

Result based in other column using pandas aggregation

我正在 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)

我想向此聚合中添加一个新列,作为结果给出项目的名称,最多 'value' 被观察到。预期结果如下:

                 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