`error: unbalanced parenthesis` while checking if an item presents in a pandas dataframe

`error: unbalanced parenthesis` while checking if an item presents in a pandas dataframe

df=pd.DataFrame({"A":["one","two","three"],"B":["fopur","give","six"]})

当我这样做时,

df.B.str.contains("six").any()
out[2]=True

当我这样做时,

df.B.str.contains("six)").any()

我收到以下错误,

C:\ProgramData\Anaconda3\lib\sre_parse.py in parse(str, flags, pattern)
    868     if source.next is not None:
    869         assert source.next == ")"
--> 870         raise source.error("unbalanced parenthesis")
    871 
    872     if flags & SRE_FLAG_DEBUG:

error: unbalanced parenthesis at position 3

请帮忙!

您需要通过 \ 转义 ) 因为特殊的正则表达式字符:

df.B.str.contains("six\)").any()

更一般:

import re

df.B.str.contains(re.escape("six)")).any()

您可以在in pandas.Series.str.contains中设置regex=False:

df.B.str.contains("six)", regex=False).any()

如果想不分大小写匹配,

df.B.str.contains("Six)", case=False, regex=False).any() 
out[]: True

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html

信息:

圆括号是正则表达式中的特殊字符,需要"escaped",例如见here or here.