python - 如果 Pandas 系列中包含列表中的单词,则替换部分字符串的最快方法

标签 python pandas list replace

我有一个大型数据集 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) 是相似的,但是我的问题是不同的,因为:

  • 这里只有一大段文字,而我有 具有许多不同行的数据集

  • 我想替换单词,而不仅仅是查找单词。

最佳答案

假设 all_transcripts 是一个 pandas DataFrame:

all_transcripts['msgText'].str.replace('|'.join(gemeentes),'woonplaats')

例子:

all_transcripts = pd.DataFrame([['this is my first message'],
                                ['second message is here'],
                                ['this is my third message']],
                               columns=['msgText'])
gemeentes = ['first','second','third']

all_transcripts['msgText'].str.replace('|'.join(gemeentes),'woonplaats')

输出

0    this is my woonplaats message
1       woonplaats message is here
2    this is my woonplaats message

关于python - 如果 Pandas 系列中包含列表中的单词,则替换部分字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934510/

相关文章:

c++ - C++ 中的列表函数

r - 在 R 中的数据框列表中更改列名称的子集

jQuery 树遍历 - 将无序列表元素嵌套到 JSON

python - 使用 boto3 从本地计算机连接到 AWS SNS。

python - 如何从多个 numpy 数组中创建一个 pandas 数据框

python - 分组 Pandas 数据框中的 If 语句

python Pandas : list of sublist: total items number

python - 使用字典使用 matplotlib 绘制条形图

python - 简单的 Tensorflow 示例在 Jupyter Notebook 中不起作用

python:for 循环和类