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

如何在Pandas DataFrame中映射权重规则并计算乘积生成Value列?

Pandas 计算权重乘积生成新列

核心思路

先为每个列的Right/Wrong定义权重映射,再通过列转换或行遍历的方式计算乘积,替代硬编码的方式。

具体实现

1. 定义权重映射字典

根据业务规则为每个列单独设置权重(示例按你的需求配置):

import pandas as pd

# 假设你的DataFrame为df
weight_maps = {
    'col1': {'Right': 5, 'Wrong': 10},  # Wrong的权重可根据实际需求调整
    'col2': {'Right': 20, 'Wrong': 100},
    'col3': {'Right': 20, 'Wrong': 100},
    'col4': {'Right': 100, 'Wrong': 50}
}

2. 方法一:生成中间权重列后相乘

这种方式直观,便于调试中间结果:

# 将每个列的字符串值替换为对应权重
df['col1_weight'] = df['col1'].map(weight_maps['col1'])
df['col2_weight'] = df['col2'].map(weight_maps['col2'])
df['col3_weight'] = df['col3'].map(weight_maps['col3'])
df['col4_weight'] = df['col4'].map(weight_maps['col4'])

# 计算每行的权重乘积
df['Value'] = df[['col1_weight', 'col2_weight', 'col3_weight', 'col4_weight']].prod(axis=1)

# 可选:删除中间权重列
# df.drop(['col1_weight', 'col2_weight', 'col3_weight', 'col4_weight'], axis=1, inplace=True)

3. 方法二:一行式计算(无中间列)

如果不需要中间权重列,用apply直接计算:

df['Value'] = df.apply(
    lambda row: (weight_maps['col1'][row['col1']] *
                 weight_maps['col2'][row['col2']] *
                 weight_maps['col3'][row['col3']] *
                 weight_maps['col4'][row['col4']]),
    axis=1
)

验证示例

对于你给出的Right_Wrong_Wrong_Right组合:

  • 按配置的权重计算:5 × 100 × 100 × 100 = 5000000,结果会正确生成在Value列中。

这种方式的优势是:后续调整权重、新增列时,只需要修改weight_maps字典,无需改动计算逻辑,比硬编码更易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:55:03