本文介绍了Pandas DataFrame 迭代行和求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个熊猫数据帧:
recipe_name ingredient_group weight%
pudding milk 0.60
pudding 2 sugar 0.10
pudding 2 sugar 0.70
pudding 2 milk 0.30
pudding 3 egg 0.20
我想要一个像这样的 Pandas DataFrame:
I would like a pandas DataFrame like this:
recipe_name ingredient_group weight% new_column
pudding milk 0.60 0.60
pudding 2 sugar 0.10 0.80 (0.1+0.7)
pudding 2 sugar 0.70 0.80 (0.1+0.7)
pudding 2 milk 0.30 0.30
pudding 3 egg 0.20 0.20
问题是有些食谱多次使用相同的成分(例如布丁 2 使用 2 倍的糖).
The problem is that there are recipes that use the same ingredient multiple times (for example pudding 2 uses 2 times sugar).
我想创建一个额外的列,其中包含重量百分比,然后是使用两次的成分的总和(参见上面的示例).
I would like to create an extra column with the weight% and then with the sum of an ingredient that was used twice (see example above).
我试图为这个问题做一个 for 循环,但我没有成功.任何人的想法?
I tried to make a for loop for this problem, but I didn't succeed. Anyone an idea?
推荐答案
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
这篇关于Pandas DataFrame 迭代行和求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!