Pandas.str.replace和不区分大小写



在以下示例中,使替换不区分大小写似乎没有效果(我想用jr替换jr.jr(:

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

为什么?我误解了什么?

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

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

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


从源代码中可以清楚地看到,如果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,以便替换是基于正则表达式的。

最新更新