首页 > 解决方案 > 熊猫为分组计数的平均值创建列

问题描述

我有一个分组数据框,如下所示:

 player_id  shot_type  count
    01         03        3
    02         01        3
               03        2
    03         01        4

我想添加一个附加列,它是 player_id 的 shot_type 计数的平均值,如下所示:

 player_id  shot_type  count  mean_shot_type_count_player
    01         03        3            (3+2)/2
    02         01        3            (3+4)/2
               03        2            (3+2)/2
    03         01        4            (3+4)/2

标签: pythonpandas

解决方案


使用GroupBy.transform

df['mean_shot_type_count_player']=df.groupby('shot_type')['count'].transform('mean')
print(df)

输出:

   player_id  shot_type  count  mean_shot_type_count_player
0         01         03      3                          2.5
1         02         01      3                          3.5
2                    03      2                          2.5
3         03         01      4                          3.5

推荐阅读