Using a variable within a regular expression in Pandas str.contains()

牧云@^-^@ 提交于 2019-12-11 03:35:51

问题


I'm attempting to select rows from a dataframe using the pandas str.contains() function with a regular expression that contains a variable as shown below.

df = pd.DataFrame(["A test Case","Another Testing Case"], columns=list("A"))
variable = "test"
df[df["A"].str.contains(r'\b' + variable + '\b', regex=True, case=False)] #Returns nothing

While the above returns nothing, the following returns the appropriate row as expected

df[df["A"].str.contains(r'\btest\b', regex=True, case=False)] #Returns values as expected

Any help would be appreciated.


回答1:


Both word boundary characters must be inside raw strings. Why not use some sort of string formatting instead? String concatenation as a rule is generally discouraged.

df[df["A"].str.contains(fr'\b{variable}\b', regex=True, case=False)] 
# Or, 
# df[df["A"].str.contains(r'\b{}\b'.format(variable), regex=True, case=False)] 

             A
0  A test Case



回答2:


I had the exact same problem when parsing a 'variable' to str.contains(variable).

Try using str.contains(variable, regex=False)

It worked for me perfectly.



来源:https://stackoverflow.com/questions/53622104/using-a-variable-within-a-regular-expression-in-pandas-str-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!