熊猫替换不匹配的子字符串

时间:2021-03-22 07:10:26

标签: python pandas dataframe

我正在尝试删除 Pandas 数据框中的一些子字符串。但是,即使 regex=True

我的数据帧开始为:

0                     0                @VirginAmerica What @dhepburn said.
3                    -1  @VirginAmerica it's really aggressive to blast...
4                    -1  @VirginAmerica and it's a really big bad thing...

如果我尝试使用 df = df.replace(r'@VirginAmerica', '', regex=True) 行,它似乎没有效果。但是,如果我尝试匹配整行,例如 df = df.replace(r'@VirginAmerica What @dhepburn said.', '', regex=True),它会导致:

0                     0                                                   
3                    -1  @VirginAmerica it's really aggressive to blast...
4                    -1  @VirginAmerica and it's a really big bad thing...

有什么我可以尝试的方法或我错过的方法来让它匹配子字符串吗?

2 个答案:

答案 0 :(得分:0)

由于您要替换的子字符串位于每个字符串的开头,我建议您尝试按如下方式完成您的语句(就在@ 之前):

df = df.replace(r'^@VirginAmerica', '', regex=True)

答案 1 :(得分:0)

原来我在程序的前面使用了 df = df.convert_dtypes() 并且它以某种方式破坏了 df.replace 中的正则表达式读取。我刚刚删除了它,它起作用了。