熊猫替换和不区分大小写

时间:2018-12-20 07:10:40

标签: python regex string pandas replace

在以下示例中,使替换大小写不敏感似乎没有任何效果(我想用 jr替换 jr。 Jr。 ):

In [0]: pd.Series('Jr. eng').str.replace('jr.', 'jr', regex=False, case=False)
Out[0]: 0    Jr. eng

为什么?我有什么误会?

1 个答案:

答案 0 :(得分:3)

使用case自变量实际上是代替指定flags=re.IGNORECASE的一种便利。如果替换不是基于正则表达式的,则与替换无关。

因此,当regex=True时,这些是您可能的选择:

pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', regex=True, case=False)
# pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', case=False)

0    jr eng
dtype: object

或者,

pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', regex=True, flags=re.IGNORECASE)
# pd.Series('Jr. eng').str.replace(r'jr\.', 'jr', flags=re.IGNORECASE)

0    jr eng
dtype: object

通过将不区分大小写的标志作为?i的一部分纳入模式,您也可以变得轻松自如并绕过两个关键字参数。见

pd.Series('Jr. eng').str.replace(r'(?i)jr\.', 'jr')
0    jr eng
dtype: object
  

注意
  您需要在正则表达式模式下转义句点\.,因为   未转义的点是一个具有不同含义的元字符(匹配   任何字符)。如果您想动态地转义模式中的元字符,可以使用re.escape

有关标志和锚点的更多信息,请参见this section of the docsre HOWTO


source code可以明显看出,如果regex=False,则忽略“ case”自变量。见

# Check whether repl is valid (GH 13438, GH 15055)
if not (is_string_like(repl) or callable(repl)):
    raise TypeError("repl must be a string or callable")

is_compiled_re = is_re(pat)
if regex:
    if is_compiled_re:
        if (case is not None) or (flags != 0):
            raise ValueError("case and flags cannot be set"
                             " when pat is a compiled regex")
    else:
        # not a compiled regex
        # set default case
        if case is None:
            case = True

        # add case flag, if provided
        if case is False:
            flags |= re.IGNORECASE
    if is_compiled_re or len(pat) > 1 or flags or callable(repl):
        n = n if n >= 0 else 0
        compiled = re.compile(pat, flags=flags)
        f = lambda x: compiled.sub(repl=repl, string=x, count=n)
    else:
        f = lambda x: x.replace(pat, repl, n)

您可以看到case参数仅在if语句中被选中。

IOW,唯一的方法是确保regex=True以便替换基于正则表达式。