【问题标题】:groupby 1 column and sum of other columns as new dataframe pandasgroupby 1 列和其他列的总和作为新的数据框 pandas
【发布时间】:2017-07-26 18:22:15
【问题描述】:

我有一个熊猫数据框:

id    won    lost  match
v1     1       0     1
v1     2       1     3
v1     0       5     8
v2     3       1     7
v2     5       5     12

我想按 id 分组并对其他列求和,例如我得到一个 df

id    total_won    total_lost    total_match
v1      3              6             12
v2      8              6             19

我如何使用 pandas groupby 和 sum 运算来对多列求和。 我试过用这个:

pd.groupby('id')['won'].sum()
pd.groupby('id')['lost'].sum()
pd.groupby('id')['match'].sum()

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用不带定义列的groupby - 将所有numeric columns 聚合起来,然后将add_prefix 和最后一个reset_index 聚合起来:

    df1 = df.groupby('id').sum().add_prefix('total_').reset_index()
    print (df1)
       id  total_won  total_lost  total_match
    0  v1          3           6           12
    1  v2          8           6           19
    

    如果需要指定多列,添加list of columns:

    cols = ['won','lost']
    df1 = df.groupby('id')[cols].sum().add_prefix('total_').reset_index()
    print (df1)
       id  total_won  total_lost
    0  v1          3           6
    1  v2          8           6
    

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 2022-07-19
      • 2019-08-10
      • 2021-09-22
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2017-09-03
      相关资源
      最近更新 更多