小编典典

Pandas替换和不区分大小写

python

使得更换不区分大小写似乎并不在下面的例子中(我要替换的效果 JR。JR ):

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

为什么?我有什么误会?


阅读 836

收藏
2021-01-20

共1个答案

小编典典

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

有关标志和锚点的更多信息,请参阅文档reHOWTO的本部分


源代码中可以很明显地看出,if忽略了“
case”参数regex=False。看到

# 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替换是基于正则表达式的。

2021-01-20