简体   繁体   English

为什么我的 str.replace() 不替换这个字符串?

[英]Why isn't my str.replace() replacing this string?

I am simply trying to remove the string 'co ' (with space after 'co') from a pandas series:我只是想从熊猫系列中删除字符串'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

Applying str.replace() and recording result to new column string_clean :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

The co is not removed. co不会被删除。

You can omit regex=False , because in Series.str.replace is default regex=True for substring replacement:您可以省略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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM