Biswankar Das
Biswankar Das

Reputation: 21

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?

Upvotes: 1

Views: 1400

Answers (1)

jezrael
jezrael

Reputation: 863301

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

Upvotes: 2

Related Questions