如何在DataFrame商品标题中匹配关键词并返回对应商品类型?
问题描述
现有两个Pandas DataFrame:
- df_product_titles:包含商品标题列
product_title blue phn small silver totebag crossshldr bag crossshldr tote
- df_product_types:包含关键词与对应商品类型的映射
search_keyword product_type phn phone tote tote bag shldr shoulder bag
需求:在df_product_titles的标题中检索df_product_types里的每个关键词,匹配到的关键词对应商品类型需返回;若标题包含多个关键词,将所有对应商品类型以逗号分隔合并为单个字符串,最终得到如下输出:
product_title product_type blue phn small phone silver totebag tote bag crossshldr bag shoulder bag crossshldr tote shoulder bag, tote bag
解决方案
可以通过Pandas的字符串匹配结合自定义函数实现,以下是具体代码:
import pandas as pd # 构造示例数据 df_product_titles = pd.DataFrame({ 'product_title': [ 'blue phn small', 'silver totebag', 'crossshldr bag', 'crossshldr tote' ] }) df_product_types = pd.DataFrame({ 'search_keyword': ['phn', 'tote', 'shldr'], 'product_type': ['phone', 'tote bag', 'shoulder bag'] }) # 定义匹配函数:遍历关键词,收集匹配到的商品类型 def get_product_types(title): matched_types = [] for idx, row in df_product_types.iterrows(): if row['search_keyword'] in title: matched_types.append(row['product_type']) return ', '.join(matched_types) # 应用函数生成结果列 df_product_titles['product_type'] = df_product_titles['product_title'].apply(get_product_types) # 输出结果 print(df_product_titles)
代码说明
- 自定义函数
get_product_types接收单个标题,遍历df_product_types的每一行关键词,检查关键词是否存在于标题中,若存在则收集对应商品类型 - 使用
apply方法将函数应用到product_title列的每一行,生成product_type列 - 最后用
join将多个匹配到的类型合并为逗号分隔的字符串
内容的提问来源于stack exchange,提问作者Marius
相关产品推荐
相关产品推荐

