使用str.replace从pandas中的字符串中删除括号

时间:2016-11-28 02:39:54

标签: regex pandas

我有一个国家名单,其中一些国家的空格是一个括号,例如玻利维亚(多民族国)。

为什么下面的代码不能只保留玻利维亚?

   energy['Country'] = energy['Country'].str.replace("Bolivia (Plurinational State of)","Bolivia")

5 个答案:

答案 0 :(得分:8)

urlpatterns = [ url(r'^index.html', render_index), url(r'^page.html', another_controller), ] 使用正则表达式执行替换。必须对括号进行转义以使它们保持简单字符:

str.replace

您可以像这样自动转义:

energy['Country'].str.replace("Bolivia \(Plurinational State of\)","Bolivia")

答案 1 :(得分:5)

这删除了括号中包含单词的所有实例:

energy['Country'] = energy['Country'].str.replace(r"\(.*\)","")

答案 2 :(得分:3)

energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","")

@python_new_user的解决方案,但解决了@Boud

提到的白色尾随问题

答案 3 :(得分:1)

energy['Country'] = (energy['Country'].str.replace(r' \(.*\)','')).str.replace('\d+', '')

这将删除括号以及括号中的内容。这也会删除国家/地区名称中的数字。

答案 4 :(得分:1)

使用@AdityaChaturvedi的解决方案,我们还可以在\s之前添加和额外添加\(,以删除括号前的空白。我正在Pandas中使用DataFrame并与一些国家一起使用,我正在处理这种特殊情况。

energy['Country'] = (energy['Country'].str.replace(r'\s\(.*\)','')).str.replace('\d+', '')