替换不匹配的子字符串

2024-05-26 22:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试删除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...

有没有什么方法可以让它匹配子字符串,或者我错过了什么


Tags: andto数据字符串truedfitwhat
2条回答

结果我在我的程序中使用了df = df.convert_dtypes(),不知何故它破坏了df.replace中的正则表达式读取。我刚把它去掉,它就成功了

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

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

相关问题 更多 >

    热门问题