Python Pandas:如何替换字符串包含“?”

时间:2017-06-16 09:26:07

标签: string python-2.7 pandas str-replace

我有一个Python 2.7 Pandas Data框架,如下所示:

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

我想用一些其他字符串替换字符串“?v =”的一部分,例如“URL”列中的“ppp”。我试过普通的替换命令:

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

但是出现了以下错误。

error: nothing to repeat.

当我尝试只替换一个字符时,例如:

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

它工作正常。当我尝试替换字符串“?v =”?

时,为什么它不起作用

2 个答案:

答案 0 :(得分: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=...

答案 1 :(得分:1)

或者,您可以指示Pandas您正在进行标准(而不是RegEx)替换:

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