Pandas replace escape character '/'

Viewed 538

I am trying to replace / using pandas and it looks like I'm facing a problem since it does not affect my DataFrame. I do realize the possible problem may be due to the fact a character / is used to escape a string in python... but how can I change the code to replace character - / to just a space... ?

Many thanks for any tips in advance.

Data['DESCRIPTION'] = Data['DESCRIPTION'].str.replace('/', ' ')
3 Answers

Try this:

Data['DESCRIPTION'] = Data['DESCRIPTION'].str.replace('//', ' ')

Since it is used to escape as you said, you need to add one additional one so it knows what to replace

Try this -

Data['DESCRIPTION'] = Data['DESCRIPTION'].str.replace(r'/', ' ')

pandas.DataFrame.replace

It is inteded to replace the entire value, not a part of string.

If you want to replace a sub string, you can either use Series' str.replace like this:

Data['DESCRIPTION'] = Data['DESCRIPTION'].str.replace(r'/', ' ')

or,

you can just apply pythons' replace method with lmabda like this:

Data['DESCRIPTION'] = Data['DESCRIPTION'].apply(lambda x: x.replace('/',' ')

Or,

You can just use str.replace to avoid using lambda:

Data['DESCRIPTION'] = Data['DESCRIPTION'].apply(str.replace, args=('/', ' '))
Related