1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > pandas算加权平均值_Pandas数据帧中多列的加权平均数

pandas算加权平均值_Pandas数据帧中多列的加权平均数

时间:2018-10-22 19:18:49

相关推荐

pandas算加权平均值_Pandas数据帧中多列的加权平均数

更一般的解决方案:

1.它为没有Student,Class的所有列创建加权平均值:df2 = df.drop('Student', axis=1) \

.groupby('Class') \

.apply(lambda x: x.drop(['Class', 'wb'], axis=1).mul(x.wb, 0).sum() / (x.wb).sum()) \

.add_suffix('_M') \

.reset_index()

print (df2)

Class V1_M V2_M V3_M

0 A 9.526316 9.157895 10.684211

1 B 3.900000 7.700000 7.900000

2 C 5.428571 2.857143 3.000000

3 D 5.631579 3.473684 5.526316

也可以为加权平均值定义列:

^{pr2}$

更一般的方法是按^{}过滤所有以V开头的列:df2 = df.groupby('Class') \

.apply(lambda x: x.filter(regex='^V').mul(x.wb, 0).sum() / (x.wb).sum()) \

.add_suffix('_M') \

.reset_index()

print (df2)

Class V1_M V2_M V3_M

0 A 9.526316 9.157895 10.684211

1 B 3.900000 7.700000 7.900000

2 C 5.428571 2.857143 3.000000

3 D 5.631579 3.473684 5.526316

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。