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!
在“文本”中,前一两个词是该人在其评论中回答的人的昵称(有时以 @ 开头,但并非总是如此)。人们回答的所有昵称都位于“名称”列中的某个位置,因为人们正在互相交谈。
我的任务是从“文本”列中删除这些名称和“@”,同时保留其余文本。
有没有办法可以使用第一列的内容过滤第二列中的文本?
先感谢您!
解决方案
这是一个使用正则表达式的解决方案。它从名称列中获取所有名称并删除@
. 然后@?
在它们前面添加,这意味着@
在正则表达式中是可选的。然后它用 将它们全部连接起来|
,这样您就可以将它们全部传递给Series.str.replace
函数,用空字符串替换它们。@
这假定text 列和 name 列中的名称之间没有一致性。如果有,还有一个更简单的解决方案。
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
推荐阅读
- html - 如何仅在 css 和 html 中滚动隐藏导航栏
- javascript - TypeError:res.render 不是函数
- python - Facetgrid 绘制堆叠归一化计数 - Seaborn
- php - 在 PHP 中使用 ODBC Microsoft Access 左连接多个表
- php - 图像无法使用 axios 在 vue js 上更新
- python - 函数调用后Python字典不清除
- python - Int 对象不可下标?
- javascript - Jquery 脚本不起作用,所以我必须修复代码
- c++ - 我可以创建一个具有特定大小的空类吗?
- c++ - 尝试将 Linux 网络功能合并到 Winsock 程序中