为了账号安全,请及时绑定邮箱和手机立即绑定

在 DataFrame 中标记品牌关键字

在 DataFrame 中标记品牌关键字

慕丝7291255 2022-10-25 14:53:39
我目前正在使用 Python 进行关键字分析。我有一个如下所示的 DataFrame df:keyword        urlcamera         canon.comcanon camera   canon.com在 SEO 中,您可以区分品牌关键字和通用关键字。现在,第一个是通用的,而第二个包含 URL 中提到的品牌名称。基于此,我想建立一个新列df['match']并根据以下条件填充它:brands = ['canon', 'canon.de']  if df['keyword'] in brands == True       df['match'] = 'brand'    else       df['match'] = 'generic'我知道语法完全错误,但我希望你能得到我想要实现的目标:keyword        url          matchcamera         canon.com    genericcanon camera   canon.com    brand
查看完整描述

1 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

keyword一个想法是在列表理解中在 splited 中进行测试,any然后通过以下方式设置新列numpy.where


mask = [any(x in y for x in x.split()) for x, y in df[['keyword', 'url']].values]

df['match'] = np.where(mask, 'brand', 'generic')

print (df)

        keyword        url    match

0        camera  canon.com  generic

1  canon camera  canon.com    brand

编辑:列表中的值可以与正则表达式Series.str.contains的连接值一起使用:|or


mask = df['keyword'].str.contains('|'.join(brands))

df['match'] = np.where(mask, 'brand', 'generic')

print (df)

        keyword        url    match

0        camera  canon.com  generic

1  canon camera  canon.com    brand


查看完整回答
反对 回复 2022-10-25
  • 1 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信