我想使用模糊匹配来检查数据帧是否包含关键字。
但是使用apply
速度非常慢。
有没有更快的方法?
我们可以使用str
或re
吗?
import regex
result = df['sentence'].apply(lambda x: regex.compile('(keyword){e<4}').findall(x)) #slow
非常感谢。
最佳答案
为什么要在 apply 内进行编译?这确实违背了它的目的。此外,加快 apply
调用速度的最佳方法是不使用 apply
。
如果没有您实际想要匹配的内容的上下文,我向您展示:
p = regex.compile('(keyword){e<4}')
result = [p.findall(x) for x in df['sentence']]
My tests show that a list comprehension based regex match supersedes str
methods in terms of performance.好吧,请对此持保留态度,因为它始终取决于您的数据以及您想要匹配的内容。
如果您只想要单个匹配项(以获得更高的性能),您可能需要考虑使用 re.search
而不是 findall。
关于python - 如何提高在数据框中使用模糊匹配的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992910/