【问题标题】:Why isn't my str.replace() replacing this string?为什么我的 str.replace() 没有替换这个字符串?
【发布时间】:2019-12-28 14:04:26
【问题描述】:

我只是想从熊猫系列中删除字符串'co '('co' 后面有空格):

x = pd.DataFrame({'string':['co hello', 'co hello','co hello', 'co hello', 'co hello']})

print(x)

     string
0  co hello
1  co hello
2  co hello
3  co hello
4  co hello

应用str.replace()并将结果记录到新列string_clean:

x['string_clean']=(x['string'].str.replace('Co ', '', case=False,regex=False))
print(x)

     string string_clean
0  co hello     co hello
1  co hello     co hello
2  co hello     co hello
3  co hello     co hello
4  co hello     co hello

co 未被删除。

【问题讨论】:

  • 因为它区分大小写? 'co' 而不是 'co'?
  • 设置regex=True
  • case 参数对非正则表达式替换没有影响。请参阅this question 了解更多信息。
  • @Erfan 是的,这行得通。但这不是正则表达式,它只是一个字符串。那么我什么时候应该使用 regex=False 或者它应该始终是 True 即使对于文字字符串?
  • 如果您在大小写上没有任何差异,只需使用:x['string'].str.replace('co', '')。如果大小写有差异,写起来更优雅:x['string'].str.replace('(?i)co', '')

标签: python pandas


【解决方案1】:

您可以省略regex=False,因为在Series.str.replace 中默认regex=True 用于子字符串替换:

x['string_clean']= x['string'].str.replace('Co ', '', case=False)
print (x)
     string string_clean
0  co hello        hello
1  co hello        hello
2  co hello        hello
3  co hello        hello
4  co hello        hello

【讨论】:

  • 好的,这行得通,但它不是正则表达式,它只是根据文档的文字字符串。这就是我设置regex=False 的原因。我什么时候应该使用regex=False?
  • @SCool - 是的,它不是正则表达式。但是对于子字符串,需要重新命名regex=True。
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2016-04-26
相关资源
最近更新 更多