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

pyt*_*ser 4 regex pandas

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

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

   energy['Country'] = energy['Country'].str.replace("Bolivia (Plurinational State of)","Bolivia")
Run Code Online (Sandbox Code Playgroud)

Bou*_*oud 8

str.replace使用正则表达式执行替换.必须转义括号以将它们保持为简单字符:

energy['Country'].str.replace("Bolivia \(Plurinational State of\)","Bolivia")
Run Code Online (Sandbox Code Playgroud)

您可以像这样自动转义:

import re
energy['Country'].str.replace(re.escape('Bolivia (Plurinational State of)'),"Bolivia")
Run Code Online (Sandbox Code Playgroud)


pyt*_*ser 6

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

energy['Country'] = energy['Country'].str.replace(r"\(.*\)","")
Run Code Online (Sandbox Code Playgroud)

  • 使用此版本,您将获得尾随空格,因为您在开括号之前没有考虑它们。 (2认同)

Hah*_*pro 6

energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","")
Run Code Online (Sandbox Code Playgroud)

@python_new_user 的解决方案,但解决了@Boud 提到的白色拖尾问题