【问题标题】:Merge rows with the same values Pandas合并具有相同值的行 Pandas
【发布时间】:2020-02-23 16:04:45
【问题描述】:

我有一个熊猫数据框如下:

您会注意到这里有很多行具有相同的code_module,code_presentation,id_student 组合 我想要做的是合并所有这些重复的行,并将sum_clicks 与每个组相加

这样的一个例子是最上面的行,它们将被合并成一行,如下所示:

         code_module code_presentation  id_student  sum_click
0                AAA             2013J       28400          18

在 SQL 术语中,私钥应该是 code_module,code_presentation,id_student 组合

在这方面的进展中,我尝试通过以下方式使用 groupby:

groupby(['id_student','code_presentation','code_module']).aggregate({'sum_click': 'sum',})

但这不起作用,因为它提供的学生 ID 甚至不在我的数据集中,我不明白为什么

此外,groupby 似乎并不是我要寻找的东西,因为它的数据结构与标准 pandas 数据框不同,而这正是我要寻找的。​​p>

问题可以在下面的输出中看到

                                        sum_click
id_student code_presentation code_module           
6516       2014J             AAA               2791
8462       2013J             DDD                646
          2014J             DDD                 10
11391      2013J             AAA                934

第 1 行和第 2 行(从 0 开始索引)应该是不同的行,而不是原来的组

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    试试这个 -

    df.groupby(['code_module', 'code_presentation', 'id_student']).agg(sum_clicks=('sum_click', 'sum')).reset_index()
    

    【讨论】:

      猜你喜欢
      • 2021-11-02
      • 2020-12-23
      • 2016-01-07
      • 2021-02-24
      • 1970-01-01
      • 2020-10-17
      • 1970-01-01
      • 2014-01-18
      • 2020-01-02
      相关资源
      最近更新 更多