[英]How to iterate through a column in data frame in python and get the arithmetic calculation corresponding to the row
Data Frame:(small data frame provided) (actual data frame is large)数据框:(提供小数据框)(实际数据框很大)
Item Type物品种类 | Item Weight产品重量 | grp cnt grp cnt |
---|---|---|
Baking Goods烘焙食品 | 4.880 4.880 | 5 5 |
Baking Goods烘焙食品 | 4.920 4.920 | 5 5 |
Baking Goods烘焙食品 | 5.260 5.260 | 5 5 |
Baking Goods烘焙食品 | 5.425 5.425 | 3 3 |
Breads面包 | 5.035 5.035 | 4 4 |
Breads面包 | 5.260 5.260 | 2 2 |
Breakfast早餐 | 7.895 7.895 | 9 9 |
Breakfast早餐 | 8.060 8.060 | 7 7 |
using above data frame calculations to be done:使用上述数据框计算来完成:
Baking Goods = [(4.880 * 5) + (4.920 * 5) + (5.260 * 5) + (5.425 * 3)]烘焙食品 = [(4.880 * 5) + (4.920 * 5) + (5.260 * 5) + (5.425 * 3)]
= (24.4 + 24.6 + 26.3 + 16.275)/(18) = (24.4 + 24.6 + 26.3 + 16.275)/(18)
Breads =[(5.035 * 2)+(5.260 * 2)]面包=[(5.035 * 2)+(5.260 * 2)]
[same calculation as 1) according to data frame] [根据数据框计算与1)相同]
[same calculation as 1) according to data frame] [根据数据框计算与1)相同]
I think you need multiple values and then aggregate sum like:我认为您需要多个值,然后汇总总和,例如:
df = df.assign(new = df['Item Weight'].mul(df['grp cnt'])).groupby('Item Type')['new'].sum()
try using groupby
and then apply
.尝试使用groupby
然后apply
。
df = df.groupby('Item Type').apply(lambda x: x.prod(axis=1).sum()/x['grp cnt'].sum())
OR或者
x = df.set_index('Item Type')
df = x.prod(axis=1).groupby('Item Type').sum().div(x.groupby('Item Type')['grp cnt'].sum())
df:东风:
Item Type
Baking Goods 5.087500
Breads 5.110000
Breakfast 7.967187
dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.