简体   繁体   中英

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM