【发布时间】:2023-03-15 06:27:01
【问题描述】:
使用: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 白色。我需要返回包含 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 方法。
非常感谢大家的支持。
【问题讨论】:
-
构建一个以数据框、列和列表作为输入的函数。然后使用链接答案中的方法返回您想要的行。类似:
def search_string(dataframe, col, words)。然后作为正文return dataframe[dataframe[col].str.contains('|'.join(words))] -
我不认为这是链接问题的重复。 OP 正在搜索包含 all 搜索词的结果,链接的问题搜索了 any 搜索词。
-
你是对的@thesilkworm,投票支持重新开放
-
@Matthew,您能否添加一些示例数据,以便我们为您重现答案。
-
重新打开的问题