我有一个国家名单,其中有些国家有一个空格,例如玻利维亚(多民族国).
为什么下面我的代码不能只保留玻利维亚?
energy['Country'] = energy['Country'].str.replace("Bolivia (Plurinational State of)","Bolivia")
Run Code Online (Sandbox Code Playgroud)
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)
这删除了括号中包含单词的所有实例:
energy['Country'] = energy['Country'].str.replace(r"\(.*\)","")
Run Code Online (Sandbox Code Playgroud)
energy['Country'] = energy['Country'].str.replace(r"\s+\(.*\)","")
Run Code Online (Sandbox Code Playgroud)
@python_new_user 的解决方案,但解决了@Boud 提到的白色拖尾问题
| 归档时间: |
|
| 查看次数: |
12253 次 |
| 最近记录: |