如何提高Pandas数据框上列表推导的速度

5

除了使用列表推导式,是否有更快的方法从集合中过滤项?对于大型数据集,列表推导式运行时间有点慢。

我已经将list_stopwords转换为集合,与列表相比,这需要更少的时间。

             date      description
0        2018-07-18    payment receipt
1        2018-07-18    ogsg s.u.b.e.b june 2018 salar
2        2018-07-18    sal admin charge
3        2018-07-19    sms alert charge outstanding
4        2018-07-19    vat onverve*issuance 


list_stopwords = set(stop_words.get_stop_words('en'))

data['description'] =  data['description'].apply(lambda x: " ".join([word for word in x.split() if word not in (list_stopwords)]))
1个回答

1

也许使用正则表达式可以更快地工作:

首先创建您的匹配案例正则表达式:


list_stopwords = set(stop_words.get_stop_words('en'))
re_stopwords= r"\b["
for word in list_stopwords: 
    re_stopwords+= "("+word+")"
re_stopwords+=r"]\b"

现在,在列上应用:

data['description'] =  data['description'].apply(lambda x: re.sub(re_stopwords,'',x))

这将用''(空字符串)替换所有停用词。

我相信它更快,因为正则表达式直接在字符串上操作,而你的代码需要在分割上循环。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接