我有一个熊猫数据框,看起来像这样:
Location Test# Type Parm1 Weight
M36 Test1 A 1.39 233
Test2 B 1.44 281
Test3 B 1.40 239
Test4 A 1.49 438
Test5 C 0.99 112
Test6 C 1.74 200
Test7 A 1.17 100
Test8 A 2.40 7.8
M37 Test1 B 2.91 232
Test2 A 20.2 0
Test3 C 4.88 958
Test4 A 9.46 0
我想计算每个位置的加权平均值,并将其作为一个额外的列添加到dataframe中,该列应如下所示:
Location Test# Type Parm1 Weight Weighted Ave.
M36 Test1 A 1.39 233 1.434
Test2 B 1.44 281
Test3 B 1.40 239
Test4 A 1.49 438
Test5 C 0.99 112
Test6 C 1.74 200
Test7 A 1.17 100
Test8 A 2.40 7.8
M37 Test1 B 2.91 232 4.495
Test2 A 20.2 0
Test3 C 4.88 958
Test4 A 9.46 0
有很多方法可以做到这一点,使用
groupby
。这应该是做这件事最有效的方法之一。你知道吗要以您的格式获取
Weighted Ave
列,请使用mask
-我现在提供另一种使用
agg
函数的方法。你知道吗基本上,可以通过使用df中的
numpy.average
列和Weight
列作为参数来计算加权平均值。你知道吗之后,只需使用
agg
来聚合这个lambda
函数。你也可以用apply
。你知道吗最后,只需使用
join
将加权平均值连接回原始数据帧。你知道吗最终输出:
如果你只是对加权平均值感兴趣:
相关问题 更多 >
编程相关推荐