在 pandas 的正则表达式中使用变量str.contains() [英] Using a variable within a regular expression in Pandas str.contains()
本文介绍了在 pandas 的正则表达式中使用变量str.contains()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用pandas str.contains()
函数从一个数据框中选择行,该函数带有包含如下所示变量的正则表达式。
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
任何帮助将不胜感激。
推荐答案
两个单词边界字符都必须在原始字符串内。为什么不使用某种字符串格式呢?通常不建议使用字符串串联。
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
这篇关于在 pandas 的正则表达式中使用变量str.contains()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文