熊猫根据另一列中的数据过滤列中的文本

时间:2020-05-26 10:07:32

标签: regex pandas

我正在准备社交媒体文本数据。两列如下所示:

name                text
@dnsTV2             @raisa Bullshit!
Sebastian           @dnsTV2, are you kidding?
@raisa              @dnsTV2 thanks to corona...
imax468             @oksana what do you mean by that???
oksana              raisa! It is so true!

在“文本”中,前一个或两个词是该人在其评论中回答的人的昵称(有时以@开头,但并非总是如此)。人们正在回答的所有昵称都在“名称”列中的某个位置,因为人们彼此交谈。

我的任务是从“文本”列中删除此名称和“ @”,同时保留其余文本。

有没有一种方法可以使用第一列的内容过滤第二列中的文本?

提前谢谢!

1 个答案:

答案 0 :(得分:0)

这里是使用正则表达式的解决方案。它从名称列中获取所有名称,然后删除@。然后,在它们前面添加@?,这意味着正则表达式中的可选@。然后,它使用|将它们全部连接起来,从而可以将它们全部传递给Series.str.replace函数,并用空字符串替换它们。 假定在文本列和名称列中具有@的名称之间没有一致性。如果有的话,还有一个更简单的解决方案。

import re

df = pd.DataFrame({
    'name': ['@dnsTV2', 'Sebastian', '@raisa', 'imax468', 'oksana', 'extra'],
    'text': ['@raisa Bullshit!', 
             '@dnsTV2, are you kidding?', 
             '@dnsTV2 thanks to corona...', 
             '@oksana what do you mean by that???', 
             'raisa! It is so true!',
             'this row has now nicknames']
})

regexes = '|'.join(['@?' + re.escape(name) for name in df.name.str.replace('@', '')])
df['text2'] = df['text'].str.replace(regexes, '')
df

        name                                 text  \
0    @dnsTV2                     @raisa Bullshit!   
1  Sebastian            @dnsTV2, are you kidding?   
2     @raisa          @dnsTV2 thanks to corona...   
3    imax468  @oksana what do you mean by that???   
4     oksana                raisa! It is so true!   
5      extra           this row has no nicknames   

                          text2  
0                     Bullshit!  
1            , are you kidding?  
2           thanks to corona...  
3   what do you mean by that???  
4              ! It is so true!  
5    this row has no nicknames  
相关问题