Python Pandas:错误:丢失),位置 2 处的未终止子模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41425945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas: error: missing ), unterminated subpattern at position 2
提问by Umar Yusuf
I have a dataframe which contains the characters (((
I would like to replace. But I get error after doing this:
我有一个包含(((
要替换的字符的数据框。但这样做后我得到错误:
data = [{'Title': 'set1((("a", "b", "c")))'},
{'Title': 'set2((("d", "e", "f")))'},
{'Title': 'set3((("g", "h", "i")))'},
{'Title': 'set4((("j", "k", "l")))'},
{'Title': 'set5((("m", "n", "o")))'},
{'Title': 'set6((("p", "q", "r")))'}]
df = pd.DataFrame(data)
df
# df['Title'] = df['Title'].str.replace('set', 'M') # Works correctly
df['Title'] = df['Title'].str.replace('(((', '>>') # Not working
How do I solve this error in order to to replace (((
by >>
and )))
by <<
?
如何解决此错误以替换(((
by>>
和)))
by <<
?
回答by furas
replace
in pandas
lets you use regex
and (
has special meaning in regex
so use \(
replace
inpandas
让你使用regex
,(
在regex
so use 中有特殊含义\(
df['Title'] = df['Title'].str.replace('\(\(\(', '>>')
pandas doc: pandas.Series.str.replace
Pandas文档:pandas.Series.str.replace
回答by loretoparisi
A more general solution would be to escape the input token using re.escape
更通用的解决方案是使用 re.escape
import re
inputToken = '((('
df['Title'] = df['Title'].str.replace(re.escape(inputToken), '>>')