gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:02:11 25 4
gpt4 key购买 nike

使替换大小写不敏感在以下示例中似乎没有效果(我想将 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

Note
You will need to escape the period \. in regex mode, because the unescaped dot is a meta-character with a different meaning (match any character). If you want to dynamically escape meta-chars in patterns, you can use re.escape.

有关标志和 anchor 的更多信息,请参阅 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,以便替换是基于正则表达式的。

关于python - Pandas .str.replace 和不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53863941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com