python - 熊猫为分组计数的平均值创建列
问题描述
我有一个分组数据框,如下所示:
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
解决方案
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
推荐阅读
- visual-studio-code - js-debug 中的源资产文件在 Apache Royale 上的 Visual Studio 代码中丢失
- android - NotifyDataSetChanged 方法不会刷新我的 RecyclerView Kotlin
- java - 以编程方式从 server.xml 读取解密的值
- css - @import 路径上的意外插值
- c++ - 为什么我的向量初始化使我的数组中的所有对象都相同?
- java - 无法在单个 dex 文件中容纳请求的类(# 方法:86965 > 65536)
- react-select - 如何使 react-select 可搜索始终显示清晰的指示符
- django - 在 Django 中显式实现 LEFT JOIN
- iis - 如何在 web.config 中指定文件路径以检查文件是否存在?
- python - 如何使用 python 从 pdf 文件中使用 camelot 提取表名和表?