使用:Python 3.7.3,Pandas 0.24.2
我正在使用Pandas数据框在Python中编写一些搜索功能。
我有一行代码可搜索包含列表中所有关键字的结果:
processed = df.loc[(df.Keywords.str.contains("magnetic")) & (df.Keywords.str.contains("board")) & (df.Keywords.str.contains("white"))]
我需要使搜索词动态化,即根据其中包含任意数量的单词的变量生成与此行等效的内容。
我已经在正则表达式中对此进行了编码,但是它比使用上述方法要慢得多。我可以简单地传递一个搜索词,但不能传递可变数量的词。
我还必须考虑以下事实:搜索词可能是部分的,即如果行包含“磁铁”等,则应返回“ agnet”的搜索词。
感激任何选项。
澄清:
我已经尝试使用类似的选项:
processed = df[df['Keywords'].str.contains('|'.join(search_list))]
不幸的是,它返回包含任何搜索词的任何行。即磁性
OR
板OR
白色。我需要返回包含磁性AND
板AND
白色的行。在亚马逊上搜索产品的图像,这将是最接近的比较。以下建议的结果:
我已经使用以下代码测试了以下提供的选项:
search_terms =“磁性板白”
search_terms = search_terms.lower()
search_list = search_terms.split()
start_time = time.time()
processed = df.loc[(df.Keywords.str.contains("magnetic")) & (df.Keywords.str.contains("board")) & (df.Keywords.str.contains("white"))]
print("--- Original %s seconds ---" % (time.time() - start_time))
start_time = time.time()
mask = pd.concat([df['Keywords'].str.contains(x) for x in search_list], axis=1).all(axis=1)
processed = df[mask]
print("--- Concat %s seconds ---" % (time.time() - start_time))
start_time = time.time()
processed = df[np.logical_and.reduce([df['Keywords'].str.contains(x) for x in search_list])]
print("--- Numpy reduce %s seconds ---" % (time.time() - start_time))
在我使用的数据集上,我得到了以下结果:
--- Original 0.09292888641357422 seconds ---
--- Concat 0.09293532371520996 seconds ---
--- Numpy reduce 0.11991643905639648 seconds ---
因此,我选择使用@jezrael建议的Concat DataFrame.all方法。
非常感谢大家的支持。
最佳答案
对列表理解中的所有掩码使用np.logical_and.reduce
,然后进行过滤:
processed = df[np.logical_and.reduce([df['Keywords'].str.contains(x) for x in search_list])]
concat
和DataFrame.all
的另一种解决方案:mask = pd.concat([df['Keywords'].str.contains(x) for x in search_list], axis=1).all(axis=1)
processed = df[mask]
关于python - Python Pandas多个搜索词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56966871/