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

基于指定列表统计Pandas DataFrame列值的模糊匹配命中次数

实现思路
  • 统一大小写消除匹配差异:将搜索历史列表的所有元素、TYPE列的所有取值全部转换为小写,避免大小写敏感导致的匹配遗漏
  • 逐行统计命中次数:对每个TYPE取值,遍历处理后的搜索历史列表,统计有多少个搜索词是该TYPE小写值的子字符串,累计结果即为该品类的命中次数
  • 结果落地:将统计得到的命中次数作为新列写入原始DataFrame,方便后续查看和使用
可运行代码片段
import pandas as pd

# 构造示例DataFrame
ratings_dict = {
    "TYPE": ["Testing","Headphone","Iphone","AC","Laptop","Monitor"],
}
df = pd.DataFrame(ratings_dict)

# 给定搜索历史列表
Search_history=['test','phone','lap','testing','tes','iphone','Headphone','head','Monitor','ac']

# 预处理:将所有搜索词转为小写
search_lower = [kw.lower() for kw in Search_history]

# 逐行统计每个TYPE的命中次数
df['hit_count'] = df['TYPE'].apply(lambda type_val: sum(1 for kw in search_lower if kw in type_val.lower()))

# 输出结果
print(df)
运行输出结果
TYPE  hit_count
0    Testing          3
1  Headphone          3
2     Iphone          2
3         AC          1
4     Laptop          1
5    Monitor          1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:39:03