Skip to content Skip to sidebar Skip to footer

Python Pandas: How To Replace String Contain "?"

I have a Python 2.7 Pandas Data frame like following: Id Title URL Id-1 Bruce Almighty https://www.youtube.com/watch?v=5VGyTOGxyVA Id-2 Superhero Movie

Solution 1:

You need escape ? by \:

df['URL'] = df['URL'].str.replace('\?v=', 'ppp')
print (df)
     Id            Title                                                URL
0  Id-1   Bruce Almighty        https://www.youtube.com/watchppp5VGyTOGxyVA
1  Id-2  Superhero Movie        https://www.youtube.com/watchppp3BnXz-7-y-o
2  Id-3            Taken        https://www.youtube.com/watchpppvjbfiOERDYs
3  Id-4      Forest Gump  https://www.youtube.com/watchpppeJFkCJySHdY&t=...

Another solution with Series.replace:

df['URL'] = df['URL'].replace('\?v=', 'ppp', regex=True)
print (df)
     Id            Title                                                URL
0  Id-1   Bruce Almighty        https://www.youtube.com/watchppp5VGyTOGxyVA
1  Id-2  Superhero Movie        https://www.youtube.com/watchppp3BnXz-7-y-o
2  Id-3            Taken        https://www.youtube.com/watchpppvjbfiOERDYs
3  Id-4      Forest Gump  https://www.youtube.com/watchpppeJFkCJySHdY&t=...

Solution 2:

Alternatively you can instruct Pandas that you are doing a standard (not RegEx) replace:

df['URL'] = df['URL'].str.replace('?v=', 'ppp', regex=False)

Post a Comment for "Python Pandas: How To Replace String Contain "?""