Pandas: Adding An Excel Sumif Column Like =a1/sumif(b:b,b1,a:a)
I have a pandas DataFrame like: pet treats lbs 0 cat 2 5.0 1 dog 1 9.9 2 snek 3 1.1 3 cat 6 4.5 4 dog 1 9.4 I would like to add a fourt
Solution 1:
You can using transform
df['treat_rate']=df.treats/df.groupby('pet').treats.transform('sum')
df
Out[153]:
pet treats lbs treat_rate
0 cat 2 5.0 0.25
1 dog 1 9.9 0.50
2 snek 3 1.1 1.00
3 cat 6 4.5 0.75
4 dog 1 9.4 0.50
Post a Comment for "Pandas: Adding An Excel Sumif Column Like =a1/sumif(b:b,b1,a:a)"