@@ -318,7 +318,8 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
318
318
match object and must return a replacement string to be used.
319
319
See :func:`re.sub`.
320
320
321
- .. versionadded:: 0.20.0
321
+ .. versionadded:: 0.20.0
322
+ `repl` also accepts a callable.
322
323
323
324
n : int, default -1 (all)
324
325
Number of replacements to make from start
@@ -333,22 +334,22 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
333
334
334
335
Examples
335
336
--------
336
- When `` repl`` is a string, every `` pat` ` is replaced as with
337
+ When `repl` is a string, every `pat` is replaced as with
337
338
:meth:`str.replace`. NaN value(s) in the Series are left as is.
338
339
339
- >>> Series(['foo', 'fuz', np.nan]).str.replace('f', 'b')
340
+ >>> pd. Series(['foo', 'fuz', np.nan]).str.replace('f', 'b')
340
341
0 boo
341
342
1 buz
342
343
2 NaN
343
344
dtype: object
344
345
345
- When `` repl`` is a callable, it is called on every `` pat` ` using
346
+ When `repl` is a callable, it is called on every `pat` using
346
347
:func:`re.sub`. The callable should expect one positional argument
347
348
(a regex object) and return a string.
348
349
349
350
To get the idea:
350
351
351
- >>> Series(['foo', 'fuz', np.nan]).str.replace('f', repr)
352
+ >>> pd. Series(['foo', 'fuz', np.nan]).str.replace('f', repr)
352
353
0 <_sre.SRE_Match object; span=(0, 1), match='f'>oo
353
354
1 <_sre.SRE_Match object; span=(0, 1), match='f'>uz
354
355
2 NaN
@@ -357,19 +358,19 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
357
358
Reverse every lowercase alphabetic word:
358
359
359
360
>>> repl = lambda m: m.group(0)[::-1]
360
- >>> Series(['foo 123', 'bar baz', np.nan]).str.replace(r'[a-z]+', repl)
361
+ >>> pd. Series(['foo 123', 'bar baz', np.nan]).str.replace(r'[a-z]+', repl)
361
362
0 oof 123
362
363
1 rab zab
363
364
2 NaN
364
365
dtype: object
365
366
366
- Using regex groups:
367
+ Using regex groups (extract second group and swap case) :
367
368
368
369
>>> pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
369
370
>>> repl = lambda m: m.group('two').swapcase()
370
- >>> Series(['Foo Bar Baz', np.nan ]).str.replace(pat, repl)
371
- 0 bAR
372
- 1 NaN
371
+ >>> pd. Series(['One Two Three', ' Foo Bar Baz']).str.replace(pat, repl)
372
+ 0 tWO
373
+ 1 bAR
373
374
dtype: object
374
375
"""
375
376
0 commit comments