10sha25
10sha25

Reputation: 71

replace a word present in dataframe

I have a word C++ and +. I want to remove only + if it is not attached with any other word. So basically I want to remove + and not C++. I want to apply this condition on the whole dataframe.

Can someone please tell me how to do it.

I have tried doing df['Decrip']=df['Decrip'].str.replace('+',' ') but this removes each word having +. So C++ becomes C which I don't intend to do.

Upvotes: 0

Views: 48

Answers (2)

ThePyGuy
ThePyGuy

Reputation: 18426

You can use regex (?<!\w|\+)\+, it has negative lookbehind assertion to find the occurrence that has + but not to match + of c++:

df['Decrip']=df['Decrip'].str.replace('(?<!\w|\+)\+',' ', regex=True)

Example at regex-101

You can also replace + directly:

df['Decrip']=df['Decrip'].str.replace(' + ', ' ', regex=False)

Upvotes: 1

Fergus Kwan
Fergus Kwan

Reputation: 373

pd.DataFrame.str.replace accept Regex. I cannot answer exactly which Regex format should you use as I need more information about it. But you can figure out how to use Regex using this link.

https://regex101.com/

Upvotes: 0

Related Questions