Python 将特定权重乘以列,并在新列中相加
我有三列数据,希望将不同的标量值相乘,然后将它们相加为一列。假设我想用Attibute_1乘以10,属性_2乘以5,属性_3乘以2Python 将特定权重乘以列,并在新列中相加,python,pandas,Python,Pandas,我有三列数据,希望将不同的标量值相乘,然后将它们相加为一列。假设我想用Attibute_1乘以10,属性_2乘以5,属性_3乘以2 Attribute_1 | Attribute_2 | Attribute_3 | Score | _________________________________________________________________ 10 10 15
Attribute_1 | Attribute_2 | Attribute_3 | Score |
_________________________________________________________________
10 10 15 180
5 5 10 95
是否有类似于“sumproduct”功能的优雅解决方案
例如
我不想要下面的解决方案,因为如果我有很多列和权重,我会寻找更优雅的东西
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
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