使用 str.replace 从 Pandas 中的字符串中删除括号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40836423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing parenthesis from a string in pandas with str.replace
提问by python_new_user
I have a a list of countries where some have a space an parenthesis afterfor example, Bolivia (Plurinational State of).
我有一份国家清单,其中有些国家在括号后有空格,例如,玻利维亚(多民族国)。
Why doesn't my code below work to only keep Bolivia?
为什么我下面的代码不能只保留玻利维亚?
energy['Country'] = energy['Country'].str.replace("Bolivia (Plurinational State of)","Bolivia")
回答by Boud
str.replace
uses regex to perform replacements. The parentheses must be escaped to keep them as simple characters:
str.replace
使用正则表达式执行替换。必须对括号进行转义以将它们保留为简单字符:
energy['Country'].str.replace("Bolivia \(Plurinational State of\)","Bolivia")
You can automate escaping like this:
您可以像这样自动转义:
import re
energy['Country'].str.replace(re.escape('Bolivia (Plurinational State of)'),"Bolivia")
回答by python_new_user
This removed all instances of where there were parentheses with words in them:
这删除了括号中包含单词的所有实例:
energy['Country'] = energy['Country'].str.replace(r"\(.*\)","")
回答by Haha TTpro
energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","")
Solution of @python_new_user but solve a white trailing problem mention by @Boud
@python_new_user 的解决方案,但解决了@Boud 提到的白色拖尾问题