-
-
Notifications
You must be signed in to change notification settings - Fork 18.4k
ENH: Allow literal (non-regex) replacement using .str.replace #16808 #19584
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
fe1f3ad
ENH: Allow literal (non-regex) replacement using .str.replace #16808
Liam3851 d53cf86
Add versionadded tag to regex param docstring.
Liam3851 656fd68
Move GH16808 tests to their own method.
Liam3851 a28ef8f
Fix PEP8 line length in tests.
Liam3851 c5325ae
Documentation additions/fixes.
Liam3851 a98bd34
Clarify it is "regex=False" that does not work with compiled regex.
Liam3851 09c1c9f
ENH: Allow literal (non-regex) replacement using .str.replace #16808
Liam3851 866db2f
Move GH16808 tests to their own method.
Liam3851 d0dfc6a
Clarify documentation
Liam3851 1006e96
Fixup whitespace
TomAugspurger 0b34cac
Retrigger travis-ci
Liam3851 f2198b0
move Raises
jreback 1371cef
Merge branch 'master' into PR_TOOL_MERGE_PR_19584
jreback File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -306,7 +306,7 @@ def str_endswith(arr, pat, na=np.nan): | |
return _na_map(f, arr, na, dtype=bool) | ||
|
||
|
||
def str_replace(arr, pat, repl, n=-1, case=None, flags=0): | ||
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): | ||
r""" | ||
Replace occurrences of pattern/regex in the Series/Index with | ||
some other string. Equivalent to :meth:`str.replace` or | ||
|
@@ -337,25 +337,50 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0): | |
flags : int, default 0 (no flags) | ||
- re module flags, e.g. re.IGNORECASE | ||
- Cannot be set if `pat` is a compiled regex | ||
regex : boolean, default True | ||
- If True, assumes the passed-in pattern is a regular expression. | ||
- If False, treats the pattern as a literal string | ||
- Cannot be set to False if `pat` is a compiled regex or `repl` is | ||
a callable. | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can you add a Raises section. (ValuesError if compiled with case/flags) |
||
.. versionadded:: 0.23.0 | ||
|
||
Returns | ||
------- | ||
replaced : Series/Index of objects | ||
|
||
Raises | ||
------ | ||
ValueError | ||
* if `regex` is False and `repl` is a callable or `pat` is a compiled | ||
regex | ||
* if `pat` is a compiled regex and `case` or `flags` is set | ||
|
||
Notes | ||
----- | ||
When `pat` is a compiled regex, all flags should be included in the | ||
compiled regex. Use of `case` or `flags` with a compiled regex will | ||
raise an error. | ||
compiled regex. Use of `case`, `flags`, or `regex=False` with a compiled | ||
regex will raise an error. | ||
|
||
Examples | ||
-------- | ||
When `repl` is a string, every `pat` is replaced as with | ||
:meth:`str.replace`. NaN value(s) in the Series are left as is. | ||
When `pat` is a string and `regex` is True (the default), the given `pat` | ||
is compiled as a regex. When `repl` is a string, it replaces matching | ||
regex patterns as with :meth:`re.sub`. NaN value(s) in the Series are | ||
left as is: | ||
|
||
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f.', 'ba', regex=True) | ||
0 bao | ||
1 baz | ||
2 NaN | ||
dtype: object | ||
|
||
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', 'b') | ||
0 boo | ||
1 buz | ||
When `pat` is a string and `regex` is False, every `pat` is replaced with | ||
`repl` as with :meth:`str.replace`: | ||
|
||
>>> pd.Series(['f.o', 'fuz', np.nan]).str.replace('f.', 'ba', regex=False) | ||
0 bao | ||
1 fuz | ||
2 NaN | ||
dtype: object | ||
|
||
|
@@ -397,34 +422,41 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0): | |
1 bar | ||
2 NaN | ||
dtype: object | ||
|
||
""" | ||
|
||
# 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 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 | ||
|
||
use_re = is_compiled_re or len(pat) > 1 or flags or callable(repl) | ||
|
||
if use_re: | ||
n = n if n >= 0 else 0 | ||
regex = re.compile(pat, flags=flags) | ||
f = lambda x: regex.sub(repl=repl, string=x, count=n) | ||
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) | ||
else: | ||
if is_compiled_re: | ||
raise ValueError("Cannot use a compiled regex as replacement " | ||
"pattern with regex=False") | ||
if callable(repl): | ||
raise ValueError("Cannot use a callable replacement when " | ||
"regex=False") | ||
f = lambda x: x.replace(pat, repl, n) | ||
|
||
return _na_map(f, arr) | ||
|
@@ -1596,9 +1628,9 @@ def match(self, pat, case=True, flags=0, na=np.nan, as_indexer=None): | |
return self._wrap_result(result) | ||
|
||
@copy(str_replace) | ||
def replace(self, pat, repl, n=-1, case=None, flags=0): | ||
def replace(self, pat, repl, n=-1, case=None, flags=0, regex=True): | ||
result = str_replace(self._data, pat, repl, n=n, case=case, | ||
flags=flags) | ||
flags=flags, regex=regex) | ||
return self._wrap_result(result) | ||
|
||
@copy(str_repeat) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you add a version added tag here