I have a DF that has a country column and some of that countries has “(” in it. I tried to remove all of that “(” s with this for loop:
JavaScript
x
4
1
for country in df_energy['Country']:
2
if ')' in df_energy['Country']:
3
df_energy['Country'] = df_energy['Country'].replace({'(':'', ')':''})
4
But when I print that DF again, I see all parenthesis did not removed. I’d be happy if someone say where I made a mistake.
Thanks.
Advertisement
Answer
You don’t need the loop:
JavaScript
1
2
1
df_energy['Country'] = df_energy['Country'].str.replace('[()]', '')
2
If you want to only replace matching ()
then:
JavaScript
1
2
1
df_energy['Country'] = df_energy['Country'].str.replace('((.*))', r'1')
2