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

如何在Pandas DataFrame中新增列,匹配id_plain取值获取对应code值

实现DataFrame按id_plain匹配码表新增code列

现有两个DataFrame结构如下:

import pandas as pd
import re

# 业务数据表df
df = pd.DataFrame([
    {'id': 'ab-c', 'id_plain': 'ABC'},
    {'id': 'ab-c', 'id_plain': 'ABC'},
    {'id': 'd_ef', 'id_plain': 'DEF'},
    {'id': 'gh.i', 'id_plain': 'GHI'},
    {'id': 'ab-c', 'id_plain': 'ABC'},
    {'id': 'ab-c', 'id_plain': 'ABC'},
    {'id': 'd_ef', 'id_plain': 'DEF'},
    {'id': 'gh.i', 'id_plain': 'GHI'}
])
# id_plain字段生成规则
df['id_plain'] = df['id'].map(lambda x: re.sub('[\W_]+', '', x).upper())

# 唯一值码表codes
codes = pd.DataFrame([
    {'id': 'AB_C', 'id_plain': 'ABC', 'code': 1},
    {'id': 'd_ef', 'id_plain': 'DEF', 'code': 2},
    {'id': 'GHI', 'id_plain': 'GHI', 'code': 3}
])

需求为以id_plain为关联键,将码表中对应的code值匹配写入df的新增列中,可选择以下两种方案实现:

方案1:左连接匹配(通用易读)

直接使用pandas的merge方法做左关联,仅取码表中需要的关联字段和结果字段,避免列名冲突:

df = df.merge(codes[['id_plain', 'code']], on='id_plain', how='left')

方案2:字典映射(性能更优)

先将码表转为id_plain到code的映射字典,再直接对df的id_plain列做映射,适合大体积数据的匹配场景:

# 构造映射字典
code_mapper = codes.set_index('id_plain')['code'].to_dict()
# 生成code列
df['code'] = df['id_plain'].map(code_mapper)

两种方案输出结果完全一致,最终df内容如下:

id id_plain  code
0  ab-c      ABC     1
1  ab-c      ABC     1
2  d_ef      DEF     2
3  gh.i      GHI     3
4  ab-c      ABC     1
5  ab-c      ABC     1
6  d_ef      DEF     2
7  gh.i      GHI     3

注:因codes的id_plain为唯一值,两种方案均不会出现匹配重复、行数膨胀的问题,无匹配值时默认返回NaN,符合常规业务预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:04