【问题标题】:Summing multiple rows having duplicate columns pandas [duplicate]对具有重复列的多行求和 pandas [重复]
【发布时间】:2017-05-18 18:09:41
【问题描述】:

考虑这个数据框

df = pd.DataFrame({'a': [1,2,1,3,4,2], 'c':['dd','ee','dd','as','ae','ee'], 'count':[5,9,1,6,8,3]})

   a   c  count
0  1  dd      5
1  2  ee      9
2  1  dd      1
3  3  as      6
4  4  ae      8
5  2  ee      3

如您所见,“a”列中有重复项1 and 2 重复多次。

我想像在我们做 groupby 的 sql 中一样对 pandas 中此类的计数求和。

我的最终 df 应该是这样的

   a   c  count
0  1  dd      6
1  2  ee      12
2  3  as      6
3  4  ae      8

我尝试使用 df = df.groupby('a') 但它正在返回我

<pandas.core.groupby.DataFrameGroupBy object

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要 groupbyac 并聚合 sum

    df = df.groupby(['a','c'], as_index=False)['count'].sum()
    print (df)
       a   c  count
    0  1  dd      6
    1  2  ee     12
    2  3  as      6
    3  4  ae      8
    

    但如果只需要 groupby 列 a,那么需要 aggregate 输出中需要的所有列 - 例如c 列由firstcountsum 聚合:

    df = df.groupby('a').agg({'c':'first', 'count':'sum'}).reset_index()
    print (df)
       a   c  count
    0  1  dd      6
    1  2  ee     12
    2  3  as      6
    3  4  ae      8
    

    【讨论】:

      【解决方案2】:

      你几乎拥有它

      df.groupby(['a', 'c']).sum().reset_index()
      

      产量

         a   c  count
      0  1  dd      6
      1  2  ee     12
      2  3  as      6
      3  4  ae      8
      

      【讨论】:

        猜你喜欢
        • 2019-03-25
        • 2013-06-28
        • 1970-01-01
        • 2019-08-11
        • 2019-01-25
        • 2017-08-09
        • 2018-07-27
        • 2021-02-28
        • 1970-01-01
        相关资源
        最近更新 更多