【问题标题】:remove words starting with "@" in a column from a dataframe从数据框中删除列中以“@”开头的单词
【发布时间】:2020-09-14 21:22:31
【问题描述】:

我有一个名为 tweetscrypto 的数据框,我试图从“text”列中删除以字符“@”开头的所有单词,并将结果收集到一个新列“clean_text”中。其余单词应保持完全相同:

tweetscrypto['clean_text'] = tweetscrypto['text'].apply(filter(lambda x:x[0]!='@', x.split()))

它似乎不起作用。有人可以帮忙吗?

提前致谢

【问题讨论】:

    标签: python pandas dataframe split


    【解决方案1】:
    Please `str.replace` string starting with `@`
    

    样本数据

                                           text
    0  News via @livemint: @RBI bars banks from links
    1      Newsfeed from @oayments_source: How Africa
    2                   is that bitcoin? not my thing
    
    
     tweetscrypto['clean_text']=tweetscrypto['text'].str.replace('(\@\w+.*?)',"")
    

    仍然可以捕获@ 而无需转义,如@baxx 所述

    tweetscrypto['clean_text']=tweetscrypto['text'].str.replace('(@\w+.*?)',"")
    
                        clean_text
    0  News via :  bars banks from links
    1         Newsfeed from : How Africa
    2      is that bitcoin? not my thing
    

    【讨论】:

    • 是否需要转义@ 符号?
    • 似乎str.replace("(@\w+)", "") 可以在这里工作,我有什么遗漏吗?
    • @baxx 你是对的。它会起作用的。包含为编辑
    • 有趣的是,我尝试为每个链接做同样的事情(每个单词都以“http”开头,但它似乎不起作用......我尝试了 tweetscrypto['clean_text']=tweetscrypto['text '].str.replace('(\http\w+.*?)',"") 有人知道为什么吗?非常感谢
    【解决方案2】:

    在这种情况下,为了提高可读性,最好定义一个方法而不是使用 lambda。

    def clean_text(X):
        X = X.split()
        X_new = [x for x in X if not x.startswith("@")
        return ' '.join(X_new)
    
    tweetscrypto['clean_text'] = tweetscrypto['text'].apply(clean_text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      相关资源
      最近更新 更多