跳至TLDR;在此答案的底部,简要介绍了不同之处。
如果您从实用性的角度考虑这两种方法,则很容易理解它们之间的区别。
.str.replace
是一种具有 非常
特定用途的方法-对 字符串 数据执行字符串或正则表达式替换。
OTOH .replace
更像是一种万能的瑞士军刀,可以用 任何其他东西 代替
任何 东西 (是的,这包括字符串和正则表达式)。
考虑下面的简单Dataframe,这将构成我们即将进行的讨论的基础。
# Setupdf = pd.Dataframe({ 'A': ['foo', 'another foo bar', 'baz'], 'B': [0, 1, 0]})df A B0 foo 01 another foo bar 12 baz 0这两个功能之间的主要区别可以归纳为
- 目的
- 用法
- 默认行为
使用str.replace
对一个字符串列串替换,并replace
在一个或多个列任何一般更换。
该文档市场
str.replace为“简单的字符串替换”的方法,所以在执行字符串/正则表达式替换上熊猫系列或它的列认为是“矢量化”等同于Python的字符串时,这应该是您的第一选择
replace()功能(或者
re.sub()是更准确)。
# simple substring replacementdf['A'].str.replace('foo', 'bar', regex=False)0 bar1 another bar bar2 bazName: A, dtype: object# simple regex replacementdf['A'].str.replace('ba.', 'xyz')0 foo1 another foo xyz2 xyzName: A, dtype: objectreplace适用于字符串替换和非字符串替换。而且,它还意味着一次**处理多个列(如果需要在整个Dataframe中替换值,则也可以
replace作为Dataframe方法访问)
df.replace()。
# Dataframe-wide replacementdf.replace({'foo': 'bar', 1: -1}) A B0 bar 01 another foo bar -12 baz 0str.replace
一次可以替换一件东西。replace
使您可以执行多个独立替换,即一次替换很多东西。
您只能为指定一个子字符串或正则表达式模式
str.replace。
repl可以是可调用的(请参阅文档),因此使用regex可以发挥创意,可以在某种程度上模拟多个子字符串的替换,但是这些解决方案充其量是不可靠的。
常见的pandaic(可拼凑,潘多尼克)模式是
str.replace通过使用regex OR
pipe分隔子字符串来删除多个不需要的子字符串
|,而替换字符串为
''(空字符串)。
replace当您具有repl2格式的 多个独立
替换项时,应该首选。有多种方法可以指定独立的替换项(列表,系列,字典等)。请参阅文档。
{'pat1': 'repl1','pat2':``, ...}为了说明差异,
df['A'].str.replace('foo', 'text1').str.replace('bar', 'text2')0 text11 another text1 text22 bazName: A, dtype: object更好地表示为
df['A'].replace({'foo': 'text1', 'bar': 'text2'}, regex=True)0 text11 another text1 text22 bazName: A, dtype: object在字符串操作的上下文中, str.replace
默认情况下启用正则表达式替换。replace
除非使用此regex=True
开关,否则仅执行完全匹配。
您所做的一切
str.replace,也可以做到
replace。但是,重要的是要注意两种方法的默认行为之间的以下差异。
- 子字符串替换-
str.replace
将替换每次出现的子字符串,replace
默认情况下仅执行整个单词匹配 - 正则表达式替换-
str.replace
除非指定,否则将第一个参数解释为正则表达式regex=False
。replace
恰恰相反。
对比之间的区别
df['A'].replace('foo', 'bar')0 bar1 another foo bar2 bazName: A, dtype: object和
df['A'].replace('foo', 'bar', regex=True)0 bar1 another bar bar2 bazName: A, dtype: object还值得一提的是,您 只能 在时执行字符串替换
regex=True。因此,例如,
df.replace({'foo': 'bar', 1: -1},regex=True)它将是无效的。TLDR;
总而言之,主要区别是
目的 。使用
str.replace对一个字符串列串替换,并replace在一个或多个列任何一般更换。用法 。
str.replace一次可以替换一件东西。replace使您可以执行多个独立替换,即一次替换很多东西。默认行为
。str.replace默认情况下启用正则表达式替换。replace除非使用此regex=True开关,否则仅执行完全匹配。



