繁体   English   中英

如何在python中遍历数据框中的一列,得到该行对应的算术计算

[英]How to iterate through a column in data frame in python and get the arithmetic calculation corresponding to the row

数据框:(提供小数据框)(实际数据框很大)

物品种类 产品重量 grp cnt
烘焙食品 4.880 5
烘焙食品 4.920 5
烘焙食品 5.260 5
烘焙食品 5.425 3
面包 5.035 4
面包 5.260 2
早餐 7.895 9
早餐 8.060 7

使用上述数据框计算来完成:

  1. 烘焙食品 = [(4.880 * 5) + (4.920 * 5) + (5.260 * 5) + (5.425 * 3)]

    = (24.4 + 24.6 + 26.3 + 16.275)/(18)

  2. 面包=[(5.035 * 2)+(5.260 * 2)]

[根据数据框计算与1)相同]

  1. 早餐 = [(7.895 * 9)+(8.060 * 7)]

[根据数据框计算与1)相同]

我认为您需要多个值,然后汇总总和,例如:

df = df.assign(new = df['Item Weight'].mul(df['grp cnt'])).groupby('Item Type')['new'].sum()

尝试使用groupby然后apply

df = df.groupby('Item Type').apply(lambda x: x.prod(axis=1).sum()/x['grp cnt'].sum())

或者

x = df.set_index('Item Type')
df = x.prod(axis=1).groupby('Item Type').sum().div(x.groupby('Item Type')['grp cnt'].sum())

东风:

Item Type
Baking Goods    5.087500
Breads          5.110000
Breakfast       7.967187
dtype: float64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM