You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于字典映射实现Pandas DataFrame加权求和新增列

基于权重字典实现Pandas多列加权求和新增列

示例数据与需求

现有如下Pandas DataFrame:

import pandas as pd
df = pd.DataFrame({
    'id' : [1 ,2, 3],
    'pts': [25,20,9],
    'ast': [8, 14, 7],
    'reb': [1, 4, 9],
    'oth': [5,6,7],
    'tov': [4, 2, 1]
})

需要新增一列score,计算逻辑为指定列与对应权重相乘后求和,权重字典如下:

score_dict = {'pts': 1, 'reb': 1.2, 'ast': 1.5, 'tov': -1}

已通过手动函数实现需求,但希望用字典映射的方式完成计算。

解决方案

方法1:利用dot矩阵乘法(高效推荐)

提取权重字典对应的列,与权重值做矩阵乘法,这是性能最优的实现方式:

# 提取字典中包含的列并保持对应顺序
selected_cols = df[score_dict.keys()]
# 计算加权求和结果
df['score'] = selected_cols.dot(pd.Series(score_dict))

方法2:使用apply逐行计算

如果需要更直观的逐行逻辑展示,可通过apply实现:

df['score'] = df.apply(lambda row: sum(row[col] * weight for col, weight in score_dict.items()), axis=1)

验证结果

执行代码后得到的DataFrame如下:

id  pts  ast  reb  oth  tov  score
0   1   25    8    1    5    4   34.2
1   2   20   14    4    6    2   43.8
2   3    9    7    9    7    1   29.3

内容的提问来源于stack exchange,提问作者md2614

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:10:12