在 Pandas str.contains() 中的正则表达式中使用变量
Using a variable within a regular expression in Pandas str.contains()
我正在尝试使用 pandas str.contains()
函数和包含变量的正则表达式从数据框中 select 行,如下所示。
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
虽然上面的returns什么都没有,但下面的returns符合预期的适当行
df[df["A"].str.contains(r'\btest\b', regex=True, case=False)] #Returns values as expected
如有任何帮助,我们将不胜感激。
两个词边界字符都必须在原始字符串中。为什么不使用某种字符串格式呢?通常不鼓励字符串连接。
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
我在将 'variable' 解析为 str.contains(变量)时遇到了完全相同的问题。
尝试使用 str.contains(变量,正则表达式=False)
它非常适合我。
以下命令对我有用:
df.query('text.str.contains(@variable)')
我正在尝试使用 pandas str.contains()
函数和包含变量的正则表达式从数据框中 select 行,如下所示。
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
虽然上面的returns什么都没有,但下面的returns符合预期的适当行
df[df["A"].str.contains(r'\btest\b', regex=True, case=False)] #Returns values as expected
如有任何帮助,我们将不胜感激。
两个词边界字符都必须在原始字符串中。为什么不使用某种字符串格式呢?通常不鼓励字符串连接。
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
我在将 'variable' 解析为 str.contains(变量)时遇到了完全相同的问题。
尝试使用 str.contains(变量,正则表达式=False)
它非常适合我。
以下命令对我有用:
df.query('text.str.contains(@variable)')