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

如何在Pandas中通过匹配Product ID填充Product Arch列?

嘿,我知道你卡了好几个小时,这就给你解决办法!

解决方案:基于字符串匹配填充DataFrame列

首先,先确认我们可以复现你的数据(方便你直接测试):

import pandas as pd

# 构造你的df1
df1 = pd.DataFrame({
    'Product': ['P 1K2', 'PC200', 'Modem', 'SSD5AZ'],
    'Product Arch': [None, None, None, None]
})

# 构造你的df2
df2 = pd.DataFrame({
    'Product ID': ['1K2', 'D5A'],
    'Arch ID': ['Computer', 'Enterprise']
})

接下来提供两种实用的方法,按需选择:

方法1:直观遍历匹配(适合小数据集)

先把df2转换成字典,这样查找起来更快,然后用apply遍历df1的每个Product条目,检查是否包含df2里的Product ID:

# 将df2转为"Product ID: Arch ID"的字典
arch_lookup = df2.set_index('Product ID')['Arch ID'].to_dict()

def find_matching_arch(product_name):
    # 遍历所有Product ID,检查是否在当前Product字符串中
    for product_id, arch in arch_lookup.items():
        if product_id in product_name:
            return arch
    # 没有匹配就返回原有的None
    return None

# 填充df1的Product Arch列
df1['Product Arch'] = df1['Product'].apply(find_matching_arch)

方法2:向量化正则提取(适合大数据集,效率更高)

利用pandas的字符串向量化操作,通过正则提取匹配的Product ID,再映射对应的Arch ID,比逐行循环快很多:

# 构建正则匹配模式:匹配所有df2中的Product ID
match_pattern = '|'.join(df2['Product ID'])

# 从Product列中提取匹配的Product ID(没有匹配则为NaN)
df1['temp_matched_id'] = df1['Product'].str.extract(f'({match_pattern})', expand=False)

# 用映射字典填充Arch列,最后删除临时列
arch_lookup = df2.set_index('Product ID')['Arch ID'].to_dict()
df1['Product Arch'] = df1['temp_matched_id'].map(arch_lookup)
df1 = df1.drop('temp_matched_id', axis=1)

两种方法运行后都会得到你想要的结果:

Product Product Arch
0   P 1K2         Computer
1   PC200         None
2   Modem         None
3  SSD5AZ         Enterprise

简单说明:方法1逻辑直白,容易理解;方法2用了pandas的向量化操作,避免了逐行循环,在数据量大的时候性能会好很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:40:18