【问题标题】:Removing multiple phrases from string column efficiently有效地从字符串列中删除多个短语
【发布时间】:2019-05-19 13:07:00
【问题描述】:

我想删除列中的几个单词,并且我在下面编写了运行良好的代码

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 次。如果是,有什么方法可以解决我的问题,请指导我

【问题讨论】:

    标签: python python-3.x string pandas


    【解决方案1】:

    您可以在此处使用正则表达式并将其减少为单个 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()]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 2018-12-28
      • 1970-01-01
      • 2011-01-03
      相关资源
      最近更新 更多