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

Python DataFrame:如何基于列匹配对df1与df2的Score值应用函数

解决方案

方法1:字典映射 + map 快速匹配

先从df1中提取Col 2到Score的映射关系,再用df2的Col 0匹配映射值,完成Score运算后赋值给Combined列:

import pandas as pd

# 模拟你的df1和df2(可替换为实际数据)
df1 = pd.DataFrame({
    'Col 0': ['Oslo'],
    'Col 1': ['isCapitalOf'],
    'Col 2': ['Norway'],
    'Score': [0.9],
    'Combined': [None]
})

df2 = pd.DataFrame({
    'Col 0': ['Norway'],
    'Col 1': ['highestMountain'],
    'Col 2': ['Galdhøpiggen'],
    'Score': [0.7],
    'Combined': [None]
})

# 1. 构建Col2到Score的映射字典
score_map = df1.set_index('Col 2')['Score'].to_dict()

# 2. 匹配计算(示例用乘法,可替换为其他运算)
df2['Combined'] = df2['Col 0'].map(score_map) * df2['Score']

# 3. 无匹配的行保留None
df2['Combined'] = df2['Combined'].where(df2['Col 0'].isin(score_map.keys()), None)

方法2:merge 合并计算(适配复杂/一对多匹配场景)

如果需要更灵活的匹配逻辑,或存在一个Col 2对应多个Score的情况,用merge更稳妥:

# 1. 左连接df2和df1的匹配数据
merged = df2.merge(
    df1[['Col 2', 'Score']],
    left_on='Col 0',
    right_on='Col 2',
    how='left',
    suffixes=('', '_df1')
)

# 2. 计算Score运算结果
df2['Combined'] = merged['Score'] * merged['Score_df1']

# 3. 无匹配的行填充为None
df2['Combined'] = df2['Combined'].fillna(None)

替换为自定义运算

如果需要乘法之外的逻辑,直接修改计算部分即可:

# 示例:自定义加权运算函数
def custom_calc(score_df2, score_df1):
    return (score_df2 * 0.6) + (score_df1 * 0.4)

# 用map方法适配自定义函数
df2['Combined'] = df2.apply(
    lambda row: custom_calc(row['Score'], score_map.get(row['Col 0'])) 
    if row['Col 0'] in score_map else None,
    axis=1
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:12:12