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

如何合并pandas中无重叠列、长度不同的DataFrame以匹配公司与网站信息

合并pandas DataFrame的可行方案

以下两种方案均可实现你要的合并效果,最终输出包含4个指定字段,无匹配的网站相关字段自动填充NaN。

前置准备:示例数据构造

import pandas as pd

# 公司信息表
df1 = pd.DataFrame({
    "Company": ["name1", "name2"],
    "other info 1": ["info1_1", "info1_2"]
})

# 网站信息表
df2 = pd.DataFrame({
    "Website": ["www.name1.com"],
    "other info 2": ["info2_1"]
})

方案1:模糊相似度匹配(适配公司名和网址部分重叠的场景)

  • 依赖安装:使用前执行pip install fuzzywuzzy python-Levenshtein安装匹配库
  • 实现代码:
from fuzzywuzzy import fuzz

def match_by_similarity(company_name, web_df, threshold=70):
    max_score = 0
    matched = None
    for _, row in web_df.iterrows():
        # 可自行修改为只匹配域名部分,提升准确率
        score = fuzz.partial_ratio(company_name.lower(), row["Website"].lower())
        if score > max_score and score >= threshold:
            max_score = score
            matched = row
    return matched if matched is not None else pd.Series([None, None], index=["Website", "other info 2"])

df_merged = pd.concat([
    df1,
    df1["Company"].apply(lambda x: match_by_similarity(x, df2))
], axis=1)
  • 可通过调整threshold阈值控制匹配严格度,数值越高匹配越严格。

方案2:自定义关键词检索匹配(支持指定关键词规则)

你可以自行预设每个公司对应的匹配关键词,完全适配你的业务规则:

# 自定义公司-关键词映射,可按需扩充
company_keywords = {
    "name1": ["name1", "name1官方", "name1官网"],
    "name2": ["name2", "name2科技", "name2集团"]
}

def match_by_keyword(company_name, web_df, keyword_map):
    keywords = keyword_map.get(company_name, [])
    for _, row in web_df.iterrows():
        if any(kw.lower() in row["Website"].lower() for kw in keywords):
            return row
    return pd.Series([None, None], index=["Website", "other info 2"])

df_merged = pd.concat([
    df1,
    df1["Company"].apply(lambda x: match_by_keyword(x, df2, company_keywords))
], axis=1)

效果说明

最终输出的df_merged符合你的要求,示例结果如下:

Companyother info 1Websiteother info 2
name1info1_1www.name1.cominfo2_1
name2info1_2NaNNaN

优化建议

  • 若网站数据量较大,可先提取网站域名部分做预处理,减少匹配计算量提升效率
  • 若有已知的公司-网站对应关系,可先做硬匹配,剩余数据再走模糊/关键词匹配,准确率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:24:03