我有一个与此相似的数据框:
name | points | tries | game
Alfred | 3.4 | 2 | sudoku
Alfred | 3 | 1 | sudoku
Alfred | 2.1 | 4 | tetris
Barry | 2.7 | 3 | tetris
Barry | 1.1 | 2 | sudoku
Cathy | 4.1 | 2 | tetris
Cathy | 3.3 | 2 | tetris
我试图首先按游戏分组,然后在每个不同的“游戏”中按“名称”分组,然后计算总“点数”,总“尝试次数”和每次尝试的平均分数。
我一直在阅读有关groupby的信息,但我没有一天去做所有这些事情,而同时计算每个组的得分/尝试次数。
任何帮助将不胜感激。
这是为了尝试更轻松地分析某些csv文件。我已经能够打开数据,读取数据并执行一些简单的groupby命令,但是这种多重选择和平均计算使我发疯。
答案 0 :(得分:2)
如果您使用的熊猫是0.25或更高版本,并且想使用新的NamedAgg
:
result = df.groupby(['game', 'name']).agg(
total_points = pd.NamedAgg('points', 'sum'),
total_tries = pd.NamedAgg('tries', 'sum')
)
result['avg_point_per_try'] = result['total_points'] / result['total_tries']
如果您使用的熊猫<0.25,则只需手动重命名列:
result = df.groupby(['game', 'name']).sum()
result.columns = ['total_points', 'total_tries']
result['avg_point_per_try'] = result['total_points'] / result['total_tries']
结果:
total_points total_tries avg_point_per_try
game name
sudoku Alfred 6.4 3 2.133333
Barry 1.1 2 0.550000
tetris Alfred 2.1 4 0.525000
Barry 2.7 3 0.900000
Cathy 7.4 4 1.850000