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

如何用Pandas在DataFrame中查找子串并匹配另一DataFrame对应值

解决方法

方法一:逐行匹配(适合小数据量)

直接遍历df2的每一行内容,在df1里找到能匹配的子串,取出对应的C2值。

import pandas as pd

# 构建示例数据
df1 = pd.DataFrame({
    'C1': ['apple', 'grape', 'orange', 'cherry'],
    'C2': [5, 11, 7, 9]
})

df2 = pd.DataFrame({
    'Item': ['apple soda', 'cherry cola', 'grape juice', 'apple candy', 
             'bubblegum apple', 'orange citrus', 'funky grapefruit', 'sweet banana']
})

# 定义匹配逻辑
def get_c2(item):
    # 筛选出C1子串在当前Item里的行
    matched_row = df1[df1['C1'].apply(lambda x: x in item)]
    # 有匹配就返回C2值,没有就返回空
    return matched_row['C2'].iloc[0] if not matched_row.empty else None

# 生成新列C2
df2['C2'] = df2['Item'].apply(get_c2)

print(df2)

方法二:正则提取+字典映射(适合大数据量)

用正则表达式从Item里提取出df1中的子串,再通过字典快速映射到C2值,效率比逐行循环高很多。

import pandas as pd

# 构建示例数据
df1 = pd.DataFrame({
    'C1': ['apple', 'grape', 'orange', 'cherry'],
    'C2': [5, 11, 7, 9]
})

df2 = pd.DataFrame({
    'Item': ['apple soda', 'cherry cola', 'grape juice', 'apple candy', 
             'bubblegum apple', 'orange citrus', 'funky grapefruit', 'sweet banana']
})

# 把所有C1的字符串拼成正则匹配模式
match_pattern = '|'.join(df1['C1'])
# 从Item中提取匹配的子串
df2['matched_c1'] = df2['Item'].str.extract(f'({match_pattern})', expand=False)

# 制作C1到C2的映射字典
c1_c2_map = df1.set_index('C1')['C2'].to_dict()
# 映射得到C2列,删除中间辅助列
df2['C2'] = df2['matched_c1'].map(c1_c2_map)
df2.drop('matched_c1', axis=1, inplace=True)

print(df2)

结果说明

运行代码后,df2会生成符合预期的C2列:匹配到子串的行对应df1的C2值,没有匹配的行(比如sweet banana)会显示NaN,和示例里的Null是等价的(pandas用NaN表示缺失值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:04:52