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

基于匹配列替换字段并填充NaN的多表合并技术需求

问题描述

我有两张不同大小的表格,需要在col1、col2字段值匹配的情况下,用表2的col6字段值替换表1的col3字段值;若匹配失败,则将表1的col3字段填充为NaN。

原始表格

表1

col1col2col3col 4
1357
2468
11121381

表2

col1col2col6
1345
2412
111413

预期结果

col1col2col3col 4
13457
24128
1112NaN81

解决方案(基于Pandas)

以下两种方法均可实现需求,根据数据量选择即可:

方法1:索引映射(高效适用于大数据量)

通过构建双索引的映射关系,直接匹配替换:

import pandas as pd

# 构造原始数据
df1 = pd.DataFrame({
    'col1': [1, 2, 11],
    'col2': [3, 4, 12],
    'col3': [5, 6, 13],
    'col 4': [7, 8, 81]
})

df2 = pd.DataFrame({
    'col1': [1, 2, 11],
    'col2': [3, 4, 14],
    'col6': [45, 12, 13]
})

# 以(col1, col2)为键,创建col6的映射表
mapping = df2.set_index(['col1', 'col2'])['col6']

# 替换df1的col3,匹配失败自动填充NaN
df1['col3'] = df1.set_index(['col1', 'col2']).index.map(mapping.get)
df1 = df1.reset_index(drop=True)

print(df1)

输出结果:

col1  col2  col3  col 4
0     1     3  45.0      7
1     2     4  12.0      8
2    11    12   NaN     81

方法2:左连接合并(逻辑直观)

通过左连接两张表,直接替换目标字段:

import pandas as pd

# 构造原始数据(同方法1)
df1 = pd.DataFrame({
    'col1': [1, 2, 11],
    'col2': [3, 4, 12],
    'col3': [5, 6, 13],
    'col 4': [7, 8, 81]
})

df2 = pd.DataFrame({
    'col1': [1, 2, 11],
    'col2': [3, 4, 14],
    'col6': [45, 12, 13]
})

# 左连接保留表1所有行,匹配col1和col2
merged_df = df1.merge(df2, on=['col1', 'col2'], how='left')
# 用col6替换col3,未匹配到的自动为NaN
merged_df['col3'] = merged_df['col6']
# 删除多余的col6列
result_df = merged_df.drop('col6', axis=1)

print(result_df)

输出结果与方法1完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:00:29