python - 有效地从字符串列中删除多个短语

标签 python python-3.x string pandas

我想删除专栏中的几个词,我写了下面的代码,它运行良好

finaldata['keyword'] = finaldata['keyword'].str.replace("Washington Times", "")
finaldata['keyword'] = finaldata['keyword'].str.replace("Washington Post", "")
finaldata['keyword'] = finaldata['keyword'].str.replace("Mail The Globe", "")

现在我有大约 30 个单词要删除,但我不能重复这行代码 30 次有什么办法可以解决我的问题,如果是,请指导我

最佳答案

您可以在此处使用正则表达式并将其简化为单个 replace 调用。

words = ["Washington Times", "Washington Post", "Mail The Globe"]
p = '|'.join(words)

finaldata['keyword'] = finaldata['keyword'].str.replace(p, '')

为了性能,如果数据没有 NaN,您应该考虑使用列表理解。

import re

p2 = re.compile(p)
finaldata['keyword'] = [p2.replace('', text) for text in finaldata['keyword']]

如果有NaN,可以用select,用loc重新赋值:

m = finaldata['keyword'].notna()
finaldata.loc[m, 'keyword'] = [
    p2.replace('', text) for text in finaldata.loc[m, 'keyword'].tolist()]

关于python - 有效地从字符串列中删除多个短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53844473/

相关文章:

python - 如何为每个 strip 使用不同的值初始化 numpy 2D 数组

c - C语言中如何删除字符串最后一部分

python - 如何使用 kCacheGrind 打开 python 配置文件数据?

python - 如何使用Intel RealSense D435创建高度图

python - 一旦满足条件,如何删除列表中对象的实例?

python - 如何使用 python3 创建虚拟环境

php - 在 PHP 中,如何在呈现的文本中不出现新行的情况下在多行中表达字符串文字?

c# - 添加到字符串字段

python - 将文件转换为字典?

python - 在 Pandas 中连接两个 groupby Dataframe 时出错