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

求助:如何在DataFrame中新增匹配短产品路径的列

解决方案:匹配DataFrame中的产品路径

我来帮你搞定这个需求!你需要在第一个带完整页面路径的DataFrame里新增一列,匹配第二个DataFrame中的短产品路径,这里有两种实用的方法,根据你的路径格式选就行:

先构造示例数据(和你给出的一致)

import pandas as pd

# 你的第一个DataFrame(带完整路径)
df_page_paths = pd.DataFrame({
    'PagePath': ['/product/123/sometext', '/product/234?someutminfo', '/product/112?whatever'],
    'Source': ['(Other)', '(Other)', '(Other)']
})

# 你的第二个DataFrame(短产品路径)
df_product_paths = pd.DataFrame({
    'Path': ['/product/123', '/product/234', '/product/345', '/product/456'],
    'Other stuff': ['Foo', 'Bar', 'Buzz', 'Lol']
})

方法一:正则提取匹配(适合路径格式固定的场景)

如果你的短路径都是/product/数字这种固定格式,用正则提取效率最高:

# 从PagePath中提取出/product/xxx的基础路径部分
df_page_paths['matched_Path'] = df_page_paths['PagePath'].str.extract(r'(/product/\d+)')

# 要是还需要把df_product_paths里的其他信息也带过来,就用merge合并
final_df = df_page_paths.merge(df_product_paths, left_on='matched_Path', right_on='Path', how='left')

运行后,final_df里的matched_Path就是匹配到的短路径,没有匹配的会显示NaN,同时也会带上对应的Other stuff列。

方法二:灵活前缀匹配(适合路径格式不固定的场景)

如果产品路径后面的内容格式多样(比如既有子目录又有URL参数),或者路径里不全是数字,用startswith来检查前缀更灵活:

def get_matching_short_path(full_path):
    # 遍历所有短路径,找第一个匹配前缀的
    for short_path in df_product_paths['Path']:
        if full_path.startswith(short_path):
            return short_path
    # 没有匹配的返回None
    return None

# 给df_page_paths新增匹配列
df_page_paths['matched_Path'] = df_page_paths['PagePath'].apply(get_matching_short_path)

# 同样可以合并获取其他信息
final_df = df_page_paths.merge(df_product_paths, left_on='matched_Path', right_on='Path', how='left')

这种方法不管完整路径后面是/sometext还是?xxx,只要开头和短路径一致就能匹配上。

最终效果

处理后的final_df会是这样:

PagePathSourcematched_PathPathOther stuff
0/product/123/sometext(Other)/product/123/product/123Foo
1/product/234?someutminfo(Other)/product/234/product/234Bar
2/product/112?whatever(Other)NaNNaNNaN

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:19:12