删除字符串中的括号区域

2024-04-29 16:26:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试:

还有几个国家的名称中有数字和/或括号。一定要把这些拿走

例如

“古巴(加勒比岛)”应该是“古巴”

数据帧输入

    Country                         Energy    
18  Mexico                          321000000   
19  Cuba (Island of Caribeas)      102000000    
20  Algeria                        1959000000   
21  American                        2252661245  
22  Andorra(no mentioned)            9000000    

我想得到这个df(df out)

   Country                           Energy    
18  Mexico                          321000000   
19  Cuba                           102000000    
20  Algeria                        1959000000   
21  American                        2252661245  
22  Andorra                         9000000

我正在尝试这个

for item in df['Country']: #remove the () with the data inside
   re.sub(r" ?\(\w+\)", "", item)

但是我的DF没有任何变化,也没有错误,所以我不知道我做错了什么。有人能帮我吗


Tags: the数据名称df数字国家itemcountry
2条回答

这可能是个开始。。。 尝试:

df['Country'] = df['Country'].apply(lambda x: re.sub(r" ?\(\w+\)", "", x))

这将把表达式应用于df['Country']中的每个值

正则表达式不太正确-如果括号中有空格怎么办

import pandas as pd

s = pd.Series(['Cuba (Island of Caribeas)', 'Andorra(no mentioned)', 'Algeria'])

s.replace(r" ?\((?:\w+ ?)+\)", "", regex=True)  

这将返回:

Out[13]: 
0       Cuba
1    Andorra
2    Algeria
dtype: object

要使其适应您的示例:

df['Country'] = df['Country'].replace(r" ?\((?:\w+ ?)+\)", "", regex=True)

相关问题 更多 >