Skip to content
Advertisement

How to replace any number of special characters with a space in a dataframe column

I have a column in Pandas that has a number of @ characters in between words. The number of consecutive @ is random and I can’t replace them with a single space not blank space since it would create cases such as

Original string Replacing with ” Replacing with ‘_’ or single space
Sun is@@@@yellow Sun isyellow Sun is____yellow

I want to convert the above string into – ‘Sun is yellow’

Is there a way to do thisfor the entire string column?

Advertisement

Answer

If need replace one or multiple @ to one space use regex [@]+:

df['New string'] = df['Original string'].replace(r'[@]+', ' ', regex=True)
print (df)
    Original string     New string
0  Sun is@@@@yellow  Sun is yellow
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement