FutureWarning:正则表达式的默认值将在未来版本中从 True 变为 False

Aki*_*ira 13 python regex string python-3.x pandas

我正在运行下面的代码来清理文本

import pandas as pd

def not_regex(pattern):
        return r"((?!{}).)".format(pattern)
    
tmp = pd.DataFrame(['No one has a European accent either @',
                    'That the kid   reminds me of Kevin'])

tmp[0].str.replace(not_regex('(\\b[-/]\\b|[a-zA-Z0-9])'), ' ') 
Run Code Online (Sandbox Code Playgroud)

然后它返回一个警告

<ipython-input-8-ef8a43f91dbd>:9: FutureWarning: The default value of regex will change from True to False in a future version.
  tmp[0].str.replace(not_regex('(\\b[-/]\\b|[a-zA-Z0-9])'), ' ')
Run Code Online (Sandbox Code Playgroud)

你能详细说明这个警告的原因吗?

Rys*_*ech 22

请参阅Pandas 1.2.0 发行说明

在未来版本中,regex for的默认值Series.str.replace()将从True更改为False。此外,当设置regex=True时,单字符正则表达式不会被视为文字字符串(GH24804

即,现在明确使用正则表达式:

dframe['colname'] = dframe['colname'].str.replace(r'\D+', regex=True)
Run Code Online (Sandbox Code Playgroud)

  • 这是否意味着如果您不使用正则表达式,您不应该介意此警告? (3认同)
  • @Paradigm我认为您替换固定字符串,在所有“replace”调用中使用“regex=False”作为第三个参数。 (2认同)