How to replace will work in pandas dataframe?

Question:

Hi I have dataframe in which I have to replace certain thing but not with all values. Please help how can achieve. Please see below example-

Example-

df:

Col
N//A
P//D
https://cg.com
C//A

Final Output-

df:

Col
N/A
P/D
https://cg.com
C/A

I used df.replace('//', '/', inplace=True) but it is replacing all.

Asked By: Shivika

||

Answers:

Use a regex with lookbehind to exclude the replacement if the // is preceded by ::

df.replace(r'(?<!:)//', '/', regex=True, inplace=True)

Output:

              Col
0             N/A
1             P/D
2  https://cg.com
3             C/A
Answered By: mozway