python - Pandas 错误转义 %s"% escape, len(escape)

标签 python pandas

执行以下行时:

df = df[df['Directory'].str.contains("C:\Windows\System32\Tasks")]

我收到以下错误:

File "/Users/patrickmaynard/Desktop/CSVparser/parse.py", line 80, in parseFoundFiles
    df = df[df['Directory'].str.contains("C:\Windows\System32\Tasks")]
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/strings.py", line 1562, in contains
    regex=regex)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pandas/core/strings.py", line 249, in str_contains
    regex = re.compile(pat, flags=flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 233, in compile
    return _compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 856, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, False)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 415, in _parse_sub
    itemsappend(_parse(source, state, verbose))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 501, in _parse
    code = _escape(source, this, state)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_parse.py", line 401, in _escape
    raise source.error("bad escape %s" % escape, len(escape))
sre_constants.error: bad escape \T at position 19

我尝试过其他文件路径,它们工作得很好。我没有包含更多代码,因为我确信它没有影响这一行。我相信这可能是 pandas 或正则表达式中的一些奇怪的故障,是这种情况还是我犯了错误?

最佳答案

str.contains 默认情况下尝试使用正则表达式,因此 \T 尝试将其读取为特殊字符。您可以告诉它不要使用正则表达式,并通过输入 regex=False 来搜索您的确切字符串:

df[df['Directory'].str.contains("C:\Windows\System32\Tasks", regex=False)]

示例:

>>> df
                       Directory
0  C:\Windows\System32\Tasks\123
1  C:\Windows\System32\Tasks\456
2                    C:\Windows\
3                            xyz

>>> df[df['Directory'].str.contains("C:\Windows\System32\Tasks", regex=False)]
                       Directory
0  C:\Windows\System32\Tasks\123
1  C:\Windows\System32\Tasks\456

关于python - Pandas 错误转义 %s"% escape, len(escape),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51772905/

相关文章:

python - 根据条件重置累计计数

python - Pandas :数据透视表

python - 基于标签的索引 Pandas (.loc)

python - 在 PyInstaller 中找不到导入的模块

Python 用相同的字符串填充列表

python - 应用具有多个参数的函数来创建一个新的 pandas 列

python - 添加一列与其他两列匹配,一列包含代表值

python - 将值分配给 pandas 数据框中的不可散列列表

python - 如何从Python中的文件名中提取时间戳?

python - 延迟调用函数