Python Pandas: How to replace string contain “?”

孤街醉人 提交于 2021-01-27 19:40:14

问题


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   https://www.youtube.com/watch?v=3BnXz-7-y-o
Id-3    Taken             https://www.youtube.com/watch?v=vjbfiOERDYs
Id-4    Forest Gump       https://www.youtube.com/watch?v=eJFkCJySHdY&t=524s

I want to replace part of string "?v=" with some other string, for example "ppp"from the column "URL". I tried by normal replace command:

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

but got following error.

error: nothing to repeat.

When I try by replacing only one character, for example:

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

it works fine. Why it didn't work when I try to replace string "?v=" ?


回答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=...



回答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)


来源:https://stackoverflow.com/questions/44585636/python-pandas-how-to-replace-string-contain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!