2017-06-16 87 views
2

我有一個Python 2.7熊貓數據幀像以下:Python熊貓:如何替換字符串包含「?」

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 

我想從列「URL」與其他字符串來替換字符串的一部分的「v =?」,例如「PPP」。我試過用普通的替換命令:

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

但是得到了下面的錯誤。

error: nothing to repeat. 

當我嘗試通過更換隻有一個字符,例如:

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

它工作正常。爲什麼當我嘗試替換字符串「?v =」時它不起作用?

+1

你正在嘗試替換'?= v'而不是'?v =' – HH1

+0

謝謝。編輯錯誤 – raja

回答

3

你需要逃避?通過\

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

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=... 
+0

謝謝。但是,當我試圖只替換「?」時,它爲什麼會起作用?字符? – raja

+0

因爲它是特殊的正則表達式字符。檢查[this](https://stackoverflow.com/questions/12766953/python-regex-with-question-mark-literal)。 – jezrael

1

或者您可以指導你正在做一個標準的(不是正則表達式)熊貓取代:

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