本文介绍了将特定权重乘以列,然后在新列中相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三列数据,并且想要将不同的标量值相乘,然后将它们求和成一列.假设我想将Attibute_1乘以10,将Attribute_2乘以5,将Attribute_3乘以2
I have three columns of data and want to multiply different scalar values to each and then sum them into a column. Let's suppose I want to multiply Attibute_1 by 10, Attribute_2 by 5, and Attribute_3 by 2
Attribute_1 | Attribute_2 | Attribute_3 | Score |
_________________________________________________________________
10 10 15 180
5 5 10 95
是否有一种类似于"sumproduct"功能的优雅解决方案?
Is there an elegant solution that is similar to a "sumproduct" kind of functionality?
例如
cols = [df['Attribute_1'], df['Attribute_2'], df['Attribute_3']]
weights = [10, 5, 2]
df['Score'] = cols * weights
我不想要以下解决方案,因为如果我有许多列和许多权重,我正在寻找更优雅的东西.
I do not want the following solution because I am looking for something more elegant if I have many columns and many weights.
df['Score'] = df['Attribute_1'] * 10 + df['Attribute_2'] * 5 + df['Attribute_3'] * 2
感谢您的帮助!
推荐答案
您可以使用mul
方法:
attributes = ["Attribute_1", "Attribute_2", "Attribute_3"]
weights = [10, 5, 2]
df['Score'] = df[attributes].mul(weights).sum(1)
df
# Attribute_1 Attribute_2 Attribute_3 Score
#0 10 10 15 180
#1 5 5 10 95
这篇关于将特定权重乘以列,然后在新列中相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!