-
-
Notifications
You must be signed in to change notification settings - Fork 18.5k
ENH: Allow dictionaries to be passed to pandas.Series.str.replace #56175
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
Changes from 9 commits
b1ea8c2
573e6e4
f9fe71e
77a579e
5de632a
d472b01
eceb234
5702ea9
ab28c9e
3be3c6b
f01728f
9ca546b
591e380
bae43ed
0359039
f0dcd55
f626cfb
1f50035
a3014de
95947a5
470a648
c6f2d3a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -1395,8 +1395,8 @@ def fullmatch(self, pat, case: bool = True, flags: int = 0, na=None): | |
@forbid_nonstring_types(["bytes"]) | ||
def replace( | ||
self, | ||
pat: str | re.Pattern, | ||
repl: str | Callable, | ||
pat: str | re.Pattern | dict | None = None, | ||
repl: str | Callable | None = None, | ||
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. IIUC if a dict is passed then |
||
n: int = -1, | ||
case: bool | None = None, | ||
flags: int = 0, | ||
|
@@ -1410,11 +1410,14 @@ def replace( | |
|
||
Parameters | ||
---------- | ||
pat : str or compiled regex | ||
pat : str, compiled regex, or a dict | ||
String can be a character sequence or regular expression. | ||
Dictionary contains <key : value> pairs of strings to be replaced | ||
along with the updated value. | ||
repl : str or callable | ||
Replacement string or a callable. The callable is passed the regex | ||
match object and must return a replacement string to be used. | ||
Must have a value of None if `pat` is a dict | ||
See :func:`re.sub`. | ||
n : int, default -1 (all) | ||
Number of replacements to make from start. | ||
|
@@ -1448,6 +1451,7 @@ def replace( | |
* 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 | ||
* if `pat` is a dictionary and `repl` is not None. | ||
|
||
Notes | ||
----- | ||
|
@@ -1457,6 +1461,15 @@ def replace( | |
|
||
Examples | ||
-------- | ||
When `pat` is a dictionary, every key in `pat` is replaced | ||
with its corresponding value: | ||
|
||
>>> pd.Series(['A', 'B', np.nan]).str.replace(pat={'A': 'a', 'B': 'b'}) | ||
0 a | ||
1 b | ||
2 NaN | ||
dtype: object | ||
|
||
When `pat` is a string and `regex` is True, 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 | ||
|
@@ -1519,8 +1532,11 @@ def replace( | |
2 NaN | ||
dtype: object | ||
""" | ||
if isinstance(pat, dict) and repl is not None: | ||
raise ValueError("repl cannot be used when pat is a dictionary") | ||
|
||
# Check whether repl is valid (GH 13438, GH 15055) | ||
if not (isinstance(repl, str) or callable(repl)): | ||
if not isinstance(pat, dict) and not (isinstance(repl, str) or callable(repl)): | ||
raise TypeError("repl must be a string or callable") | ||
|
||
is_compiled_re = is_re(pat) | ||
|
@@ -1540,10 +1556,21 @@ def replace( | |
if case is None: | ||
case = True | ||
|
||
result = self._data.array._str_replace( | ||
pat, repl, n=n, case=case, flags=flags, regex=regex | ||
) | ||
return self._wrap_result(result) | ||
if isinstance(pat, dict): | ||
rhshadrach marked this conversation as resolved.
Show resolved
Hide resolved
|
||
res_output = self._data | ||
for key, value in pat.items(): | ||
result = res_output.array._str_replace( | ||
key, value, n=n, case=case, flags=flags, regex=regex | ||
) | ||
res_output = self._wrap_result(result) | ||
|
||
else: | ||
result = self._data.array._str_replace( | ||
pat, repl, n=n, case=case, flags=flags, regex=regex | ||
) | ||
res_output = self._wrap_result(result) | ||
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. I believe you can call _wrap_result just once at the end, rather than inside the for loop. 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. @rhshadrach wouldn't you need the for loop in the case that pat contained multiple key : value pairs of strings to be replaced? 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. Correct - I'm not suggesting to remove the for loop entirely. Just to call 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. So after doing a bit of debugging it looks like we need to call _wrap_result after each iteration so we can save the output of our string replace and update self._data is a Series and 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. I see - thanks for checking! 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. rather than doing the loop here, is there any immediate advantage to passing the dict onto the arrays IIUC the accessors should only be validating the passed parameters, defining the "pandas string API", providing the documentation and wrapping the array result into a Series. IMO the implementation should be at array level and then can be overridden if the array types can be optimized or use native methods. For example, maybe using "._str_map" could be faster for object type and maybe The array level optimizations need not be in this PR though. 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.
I think this is a good idea, but agreed it need not be here (this is perf neutral compared to the status quo). If not tackled here, we can throw up an issue noting the performance improvement. @rmhowe425 - thoughts? 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. Agreed! I think this idea is deserving of a separate issue. Happy to work that issue as well! |
||
|
||
return res_output | ||
|
||
@forbid_nonstring_types(["bytes"]) | ||
def repeat(self, repeats): | ||
|
Uh oh!
There was an error while loading. Please reload this page.