使用: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"))]
我需要使搜索词动态化,即根据包含任意数量单词的变量生成与此行等效的内容。
我已经设法在正则表达式中对此进行编码,但是它比使用上述方法慢得多。我可以简单地传递一个搜索词,但不能传递可变数量的词。
我还必须考虑这样一个事实,即搜索词可能是部分的,即如果行包含“magnet”等,“agnet”的搜索词应该返回。
非常感谢收到的任何选项。
澄清一下:
我已经尝试过使用如下选项:
processed = df[df['Keywords'].str.contains('|'.join(search_list))]
不幸的是,这会返回包含任何搜索词的任何行。即磁性 OR
板 OR
白色。我需要的是返回包含 Magnetic AND
Board AND
White 的行。在亚马逊上搜索产品图片,这将是最接近的比较。
以下建议的结果:
我已经使用以下代码测试了下面提供的选项:
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 Pandas 多个搜索词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56966871/