在python中提取字符串的特定部分
我试图提取熊猫系列中字符串的特定部分 例如:在python中提取字符串的特定部分,python,string,pandas,dataframe,xls,Python,String,Pandas,Dataframe,Xls,我试图提取熊猫系列中字符串的特定部分 例如: energy['Country'] 给我: 27 Aruba 28 Australia1 29 Austria 30
energy['Country']
给我:
27 Aruba
28 Australia1
29 Austria
30 Azerbaijan
31 Bahamas
32 Bahrain
33 Bangladesh
34 Barbados
35 Belarus
36 Belgium
37 Belize
38 Benin
39 Bermuda
40 Bhutan
41 Bolivia (Plurinational State of)
42 Bonaire, Sint Eustatius and Saba
我想把多民族玻利维亚国改成玻利维亚国
我的失败尝试是:
pattern = “(.*?)”
list = [re.sub(pattern, '', i) for i in energy['Country']]
energy['Country'] = list
有没有人能给我一些建议,告诉我如何修改我的代码,使之生效 这样做:
df['Country'] = df['Country'].str.replace(r"\(.*\)","")
示例数据帧上的示例:
In [91]: df
Out[91]:
Country
0 Aruba
1 Australia1
2 Bolivia (Plurinational State of)
In [93]: df['Country'] = df['Country'].str.replace(r"\(.*\)","")
In [94]: df
Out[94]:
Country
0 Aruba
1 Australia1
2 Bolivia
这样做:
df['Country'] = df['Country'].str.replace(r"\(.*\)","")
示例数据帧上的示例:
In [91]: df
Out[91]:
Country
0 Aruba
1 Australia1
2 Bolivia (Plurinational State of)
In [93]: df['Country'] = df['Country'].str.replace(r"\(.*\)","")
In [94]: df
Out[94]:
Country
0 Aruba
1 Australia1
2 Bolivia
“\”是什么意思/作用?我知道“r”表示您想要完全匹配/原始expression@Caledonian26
\(
是用来逃避偏执。什么是“\”的意思/做什么?我知道“r”的意思是你想要精确的匹配/原始的expression@Caledonian26\(
用于逃避偏执。