Skip to content

Commit a7ea439

Browse files
committed
ENH: str.replace accepts a compiled expression
.str.replace now accepts a compiled regular expression for `pat`. See #15446
1 parent 81c57e2 commit a7ea439

File tree

3 files changed

+83
-9
lines changed

3 files changed

+83
-9
lines changed

doc/source/whatsnew/v0.20.0.txt

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ New features
2828

2929
- Integration with the ``feather-format``, including a new top-level ``pd.read_feather()`` and ``DataFrame.to_feather()`` method, see :ref:`here <io.feather>`.
3030
- ``.str.replace`` now accepts a callable, as replacement, which is passed to ``re.sub`` (:issue:`15055`)
31+
- ``.str.replace`` now accepts a compiled regular expression as pattern (:issue:`15446`)
3132

3233

3334

pandas/core/strings.py

+26-9
Original file line numberDiff line numberDiff line change
@@ -311,8 +311,12 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
311311
312312
Parameters
313313
----------
314-
pat : string
315-
Character sequence or regular expression
314+
pat : string or compiled regex
315+
String can be a character sequence or regular expression.
316+
317+
.. versionadded:: 0.20.0
318+
`pat` also accepts a compiled regex.
319+
316320
repl : string or callable
317321
Replacement string or a callable. The callable is passed the regex
318322
match object and must return a replacement string to be used.
@@ -324,9 +328,10 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
324328
n : int, default -1 (all)
325329
Number of replacements to make from start
326330
case : boolean, default True
327-
If True, case sensitive
331+
If True, case sensitive. Raises if `pat` is a compiled regex.
328332
flags : int, default 0 (no flags)
329-
re module flags, e.g. re.IGNORECASE
333+
re module flags, e.g. re.IGNORECASE. Raises if `pat` is a compiled
334+
regex.
330335
331336
Returns
332337
-------
@@ -372,21 +377,33 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
372377
0 tWO
373378
1 bAR
374379
dtype: object
380+
381+
When `pat` is a compiled regex, all flags should be included in the
382+
compiled regex. Use of `case` and `flags` with a compiled regex will
383+
raise an error.
384+
385+
>>> regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE)
386+
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar')
387+
0 foo
388+
1 bar
389+
2 NaN
390+
dtype: object
375391
"""
376392

377393
# Check whether repl is valid (GH 13438, GH 15055)
378394
if not (is_string_like(repl) or callable(repl)):
379395
raise TypeError("repl must be a string or callable")
380-
use_re = not case or len(pat) > 1 or flags or callable(repl)
396+
# Check whether pat is a compiled regex or should be compiled
397+
is_compiled_re = isinstance(pat, type(re.compile("")))
398+
use_re = (is_compiled_re or not case or
399+
len(pat) > 1 or flags or callable(repl))
381400

382401
if use_re:
383402
if not case:
384403
flags |= re.IGNORECASE
385-
regex = re.compile(pat, flags=flags)
386404
n = n if n >= 0 else 0
387-
388-
def f(x):
389-
return regex.sub(repl, x, count=n)
405+
f = lambda x: re.sub(pattern=pat, repl=repl, string=x,
406+
count=n, flags=flags)
390407
else:
391408
f = lambda x: x.replace(pat, repl, n)
392409

pandas/tests/test_strings.py

+56
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,62 @@ def test_replace_callable(self):
469469
exp = Series(['bAR', NA])
470470
tm.assert_series_equal(result, exp)
471471

472+
def test_replace_compiled_regex(self):
473+
# GH 15446
474+
values = Series(['fooBAD__barBAD', NA])
475+
476+
# test with compiled regex
477+
pat = re.compile(r'BAD[_]*')
478+
result = values.str.replace(pat, '')
479+
exp = Series(['foobar', NA])
480+
tm.assert_series_equal(result, exp)
481+
482+
# mixed
483+
mixed = Series(['aBAD', NA, 'bBAD', True, datetime.today(), 'fooBAD',
484+
None, 1, 2.])
485+
486+
rs = Series(mixed).str.replace(pat, '')
487+
xp = Series(['a', NA, 'b', NA, NA, 'foo', NA, NA, NA])
488+
tm.assertIsInstance(rs, Series)
489+
tm.assert_almost_equal(rs, xp)
490+
491+
# unicode
492+
values = Series([u('fooBAD__barBAD'), NA])
493+
494+
result = values.str.replace(pat, '')
495+
exp = Series([u('foobar'), NA])
496+
tm.assert_series_equal(result, exp)
497+
498+
result = values.str.replace(pat, '', n=1)
499+
exp = Series([u('foobarBAD'), NA])
500+
tm.assert_series_equal(result, exp)
501+
502+
# flags + unicode
503+
values = Series([b"abcd,\xc3\xa0".decode("utf-8")])
504+
exp = Series([b"abcd, \xc3\xa0".decode("utf-8")])
505+
pat = re.compile(r"(?<=\w),(?=\w)", flags=re.UNICODE)
506+
result = values.str.replace(pat, ", ")
507+
tm.assert_series_equal(result, exp)
508+
509+
# case and flags provided to str.replace will have no effect
510+
# and will produce warnings
511+
values = Series(['fooBAD__barBAD__bad', NA])
512+
pat = re.compile(r'BAD[_]*')
513+
514+
with tm.assertRaisesRegexp(ValueError, "process flags argument"):
515+
result = values.str.replace(pat, '', flags=re.IGNORECASE)
516+
517+
with tm.assertRaisesRegexp(ValueError, "process flags argument"):
518+
result = values.str.replace(pat, '', case=False)
519+
520+
# test with callable
521+
values = Series(['fooBAD__barBAD', NA])
522+
repl = lambda m: m.group(0).swapcase()
523+
pat = re.compile('[a-z][A-Z]{2}')
524+
result = values.str.replace(pat, repl, n=2)
525+
exp = Series(['foObaD__baRbaD', NA])
526+
tm.assert_series_equal(result, exp)
527+
472528
def test_repeat(self):
473529
values = Series(['a', 'b', NA, 'c', NA, 'd'])
474530

0 commit comments

Comments
 (0)