Skip to content
Advertisement

Removing a char from a pandas dataframe column with for loop

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:

for country in df_energy['Country']:
    if ')' in df_energy['Country']:
        df_energy['Country'] = df_energy['Country'].replace({'(':'', ')':''})

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:

df_energy['Country'] = df_energy['Country'].str.replace('[()]', '')

If you want to only replace matching () then:

df_energy['Country'] = df_energy['Country'].str.replace('((.*))', r'1')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement