Pandas DataFrame iterating over rows and sum

后端 未结 1 816
广开言路
广开言路 2021-01-27 09:26

I have got this pandas DataFrame:

 recipe_name   ingredient_group       weight%
 pudding       milk                     0.60
 pudding 2     sugar                         


        
1条回答
  •  时光说笑
    2021-01-27 09:38

    Use groupby with transform sum:

    df['accumulated weight'] = df.groupby(['name','group'])['weight'].transform(sum)
    print (df)
        name     group  weight  accumulated weight
    0  Appie  elephant      60                  60
    1  Henry     tiger      50                 120
    2  Henry     tiger      70                 120
    3  Laura       cow      30                  30
    4  Laura     tiger      20                  20
    

    0 讨论(0)
提交回复
热议问题