我在python中有一个数据框架'energy‘,列'Country’有一个国家列表。我试图消除数字,例如,瑞士的Switzerland17和括号,例如,玻利维亚。去玻利维亚。
我为数值情况(如Switzerland17 )工作过的代码,而不是括号中的代码:
for cty in energy['Country']:
try:
y = re.findall('[0-9]',cty)[0]
energy['Country'] = energy['Country'].str.replace(cty,cty[:cty.find(str(y))])
except:
continue
上面的工作原理,但是下面没有:
for c in energy['Country']:
try:
z = re.search('[(]',c)[0]
energy['Country'] = energy['Country'].str.replace(c,c[:c.find(str(z))])
except:
continue
我还看到单独的打印(c,c:c.find(str(Z)可以工作,但在for-循环中不能工作。我发现和更换支架的地方出了什么问题?
发布于 2019-05-03 03:32:53
使用str.replace
和str.strip
Ex:
import pandas as pd
df = pd.DataFrame({'Country': ["Switzerland17", "Bolivia (KK)", "China"]})
df["Country"] = df["Country"].str.strip("0123456789").str.replace(r"(\(.*?\))", "").str.strip()
print(df)
输出:
Country
0 Switzerland
1 Bolivia
2 China
https://stackoverflow.com/questions/55968868
复制