使用str.replace从pandas中的字符串中删除括号 [英] Removing parenthesis from a string in pandas with str.replace

查看:168
本文介绍了使用str.replace从pandas中的字符串中删除括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个国家列表,其中有些国家在括号后有空格,例如玻利维亚(多民族国).

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")

推荐答案

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

str.replace uses regex to perform replacements. The parentheses must be escaped to keep them as simple characters:

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")

这篇关于使用str.replace从pandas中的字符串中删除括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆