【发布时间】:2019-05-03 11:24:44
【问题描述】:
我在 python 中有一个数据框“energy”,其中包含国家列表的“Country”列。我正在尝试消除数字,例如,瑞士 17 到瑞士以及括号,例如,玻利维亚(.. 到玻利维亚。
我为瑞士17等数字案例工作的代码,但不适用于括号:
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
我还看到单独的 print(c,c[:c.find(str(z))]) 有效,但在 for 循环中无效。查找和替换支架哪里出错了?
【问题讨论】: