【问题标题】:Average values with Pandas GroupByPandas GroupBy 的平均值
【发布时间】:2019-09-12 22:29:12
【问题描述】:

我有一个类似这样的数据框:

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 命令,但是这种多重选择和平均计算让我发疯。

【问题讨论】:

    标签: python-3.x pandas pandas-groupby


    【解决方案1】:

    如果您使用的是 pandas 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']
    

    如果您使用的是

    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
    

    【讨论】:

      猜你喜欢
      • 2021-10-20
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 2022-01-24
      • 2020-03-09
      • 1970-01-01
      相关资源
      最近更新 更多