python – 将特定权重乘以列并在新列中相加

我有三列数据,想要将不同的标量值相乘,然后将它们加到一列中.假设我想将Attibute_1乘以10,将Attribute_2乘以5,将Attribute_3乘以2

Attribute_1   |   Attribute_2   |   Attribute_3   |    Score    |
_________________________________________________________________
      10              10                15              180
       5               5                10               95

是否有一个优雅的解决方案类似于“sumproduct”类型的功能?

例如.

cols = [df['Attribute_1'], df['Attribute_2'], df['Attribute_3']]
weights = [10, 5, 2]
df['Score'] = cols * 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
点赞