【发布时间】:2019-09-19 22:00:09
【问题描述】:
我有一个大型数据集all_transcripts,有近 300 万行。 msgText 列之一包含书面消息。
>>> all_transcripts['msgText']
['this is my first message']
['second message is here']
['this is my third message']
此外,我有一个包含 200 多个单词的列表,名为 gemeentes。
>>> gemeentes
['first','second','third' ... ]
如果此列表中的某个单词包含在msgText 中,我想将其替换为另一个单词。为此,我创建了函数:
def replaceCity(text):
newText = text.replace(plaatsnaam, 'woonplaats')
return str(newText)
所以,我想要的输出应该是这样的:
['this is my woonplaats message']
['woonplaats message is here']
['this is my woonplaats message']
目前,我正在循环遍历列表,对于列表中的每个项目,应用replaceCity函数。
for plaatsnaam in gemeentes:
global(plaatsnaam)
all_transcripts['filtered_text'] = test.msgText.apply(replaceCity)
但是,这需要很长时间,因此似乎效率不高。有没有更快的方法来执行此任务?
这篇文章 (Algorithm to find multiple string matches) 类似,但我的问题不同,因为:
这里只有一小段文字,而我有一个 具有许多不同行的数据集
我想替换单词,而不仅仅是查找单词。
【问题讨论】:
-
您是否尝试过使用 pandas lambda 函数的正则表达式??
标签: python pandas list replace