Skip to content

BUG (string): str.replace with negative n #59628

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 2 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.3.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Conversion

Strings
^^^^^^^
-
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`StringDtype` with ``storage="pyarrow"`` (:issue:`59628`)
-

Interval
Expand Down
4 changes: 1 addition & 3 deletions pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,9 +350,7 @@ def _str_replace(
fallback_performancewarning()
return super()._str_replace(pat, repl, n, case, flags, regex)

func = pc.replace_substring_regex if regex else pc.replace_substring
result = func(self._pa_array, pattern=pat, replacement=repl, max_replacements=n)
return type(self)(result)
return ArrowExtensionArray._str_replace(self, pat, repl, n, case, flags, regex)

def _str_repeat(self, repeats: int | Sequence[int]):
if not isinstance(repeats, int):
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/extension/test_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1855,6 +1855,17 @@ def test_str_replace_negative_n():
expected = pd.Series(["bc", ""], dtype=ArrowDtype(pa.string()))
tm.assert_series_equal(expected, actual)

# Same bug for pyarrow-backed StringArray GH#59628
ser2 = ser.astype(pd.StringDtype(storage="pyarrow"))
actual2 = ser2.str.replace("a", "", -3, True)
expected2 = expected.astype(ser2.dtype)
tm.assert_series_equal(expected2, actual2)

ser3 = ser.astype(pd.StringDtype(storage="pyarrow", na_value=np.nan))
actual3 = ser3.str.replace("a", "", -3, True)
expected3 = expected.astype(ser3.dtype)
tm.assert_series_equal(expected3, actual3)


def test_str_repeat_unsupported():
ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
Expand Down