更新后,pandas无效的转义序列

Geo*_*ler 2 python escaping pandas deprecation-warning

我在pandas中解析带有多个字符分隔符的csv,如下所示

big_df = pd.read_csv(os.path.expanduser('~/path/to/csv/with/special/delimiters.csv'), 
                     encoding='utf8', 
                     sep='\$\$><\$\$', 
                     decimal=',', 
                     engine='python')
big_df.iloc[:, -1] = big_df.iloc[:, -1].str.replace('\$\$>$', '')
big_df = big_df.replace(['^<', '>$'], ['', ''], regex=True)

big_df.columns = big_df.columns.to_series().replace(['^<', '>$', '>\$\$'], ['', '', ''], regex=True)
Run Code Online (Sandbox Code Playgroud)

这工作正常,直到我最近升级我的熊猫安装.现在我看到很多弃用警告:

<input>:3: DeprecationWarning: invalid escape sequence \$
<input>:3: DeprecationWarning: invalid escape sequence \$
<input>:3: DeprecationWarning: invalid escape sequence \$
<input>:3: DeprecationWarning: invalid escape sequence \$
<input>:3: DeprecationWarning: invalid escape sequence \$
<ipython-input-6-1ba5b58b9e9e>:3: DeprecationWarning: invalid escape sequence \$
  sep='\$\$><\$\$',
<ipython-input-6-1ba5b58b9e9e>:7: DeprecationWarning: invalid escape sequence \$
  big_df.iloc[:, -1] = big_df.iloc[:, -1].str.replace('\$\$>$', '')
Run Code Online (Sandbox Code Playgroud)

由于我需要带$符号的特殊分隔符,我不确定如何正确处理这些警告

And*_*eak 9

问题是在字符串中转义会干扰正则表达式中的转义.虽然'\s'是一个有效的正则表达式令牌,但对于python,这将代表一个不存在的特殊字符(字符串文字'\s'自动转换为'\\s'ie r'\s',我怀疑这个过程显然是从python 3.6中被弃用的).

关键是在构造正则表达式时始终使用原始字符串文字,以确保python不会被反斜杠混淆.虽然大多数框架用于处理这种歧义(我假设通过忽略无效的转义序列),但某些库的较新版本正试图强制程序员明确且明确(我完全支持).

在您的具体情况下,您的模式应该从,例如,更改'\$\$><\$\$'r'\$\$><\$\$':

big_df.iloc[:, -1] = big_df.iloc[:, -1].str.replace(r'\$\$>$', '')
Run Code Online (Sandbox Code Playgroud)

实际发生的是反斜杠本身必须为python转义,以便'\$'在你的正则表达式模式中有一个字面长度为2的字符串:

>>> r'\$\$><\$\$'
'\\$\\$><\\$\\$'
Run Code Online (Sandbox Code Playgroud)