问题
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