Skip to content

support tuple in startswith/endswith for arrow strings #56580

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 6 commits into from
Dec 21, 2023
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.2.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@ Strings
- Bug in :meth:`Series.__mul__` for :class:`ArrowDtype` with ``pyarrow.string`` dtype and ``string[pyarrow]`` for the pyarrow backend (:issue:`51970`)
- Bug in :meth:`Series.str.find` when ``start < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56411`)
- Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56404`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for :class:`ArrowDtype` with ``pyarrow.string`` dtype (:issue:`56579`)
- Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for ``string[pyarrow]`` (:issue:`54942`)

Interval
Expand Down
30 changes: 26 additions & 4 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -2174,14 +2174,36 @@ def _str_contains(
result = result.fill_null(na)
return type(self)(result)

def _str_startswith(self, pat: str, na=None):
result = pc.starts_with(self._pa_array, pattern=pat)
def _str_startswith(self, pat: str | tuple[str, ...], na=None):
if isinstance(pat, str):
result = pc.starts_with(self._pa_array, pattern=pat)
else:
if len(pat) == 0:
# For empty tuple, pd.StringDtype() returns null for missing values
# and false for valid values.
result = pc.if_else(pc.is_null(self._pa_array), None, False)
else:
result = pc.starts_with(self._pa_array, pattern=pat[0])

for p in pat[1:]:
result = pc.or_(result, pc.starts_with(self._pa_array, pattern=p))
if not isna(na):
result = result.fill_null(na)
return type(self)(result)

def _str_endswith(self, pat: str, na=None):
result = pc.ends_with(self._pa_array, pattern=pat)
def _str_endswith(self, pat: str | tuple[str, ...], na=None):
if isinstance(pat, str):
result = pc.ends_with(self._pa_array, pattern=pat)
else:
if len(pat) == 0:
# For empty tuple, pd.StringDtype() returns null for missing values
# and false for valid values.
result = pc.if_else(pc.is_null(self._pa_array), None, False)
else:
result = pc.ends_with(self._pa_array, pattern=pat[0])

for p in pat[1:]:
result = pc.or_(result, pc.ends_with(self._pa_array, pattern=p))
if not isna(na):
result = result.fill_null(na)
return type(self)(result)
Expand Down
24 changes: 19 additions & 5 deletions pandas/tests/extension/test_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -1801,19 +1801,33 @@ def test_str_contains_flags_unsupported():
@pytest.mark.parametrize(
"side, pat, na, exp",
[
["startswith", "ab", None, [True, None]],
["startswith", "b", False, [False, False]],
["endswith", "b", True, [False, True]],
["endswith", "bc", None, [True, None]],
["startswith", "ab", None, [True, None, False]],
["startswith", "b", False, [False, False, False]],
["endswith", "b", True, [False, True, False]],
["endswith", "bc", None, [True, None, False]],
["startswith", ("a", "e", "g"), None, [True, None, True]],
["endswith", ("a", "c", "g"), None, [True, None, True]],
["startswith", (), None, [False, None, False]],
["endswith", (), None, [False, None, False]],
],
)
def test_str_start_ends_with(side, pat, na, exp):
ser = pd.Series(["abc", None], dtype=ArrowDtype(pa.string()))
ser = pd.Series(["abc", None, "efg"], dtype=ArrowDtype(pa.string()))
result = getattr(ser.str, side)(pat, na=na)
expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize("side", ("startswith", "endswith"))
def test_str_starts_ends_with_all_nulls_empty_tuple(side):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added this test because in case of empty tuple, code to create series is:

result = pc.if_else(pc.is_null(self._pa_array), None, False)

I thought that if self._pa_array was all nulls, that resulting datatype may be null[pyarrow] (when we want bool[pyarrow]), I added this test to validate that bool is preserved, even in all nulls case.

ser = pd.Series([None, None], dtype=ArrowDtype(pa.string()))
result = getattr(ser.str, side)(())

# bool datatype preserved for all nulls.
expected = pd.Series([None, None], dtype=ArrowDtype(pa.bool_()))
tm.assert_series_equal(result, expected)


@pytest.mark.parametrize(
"arg_name, arg",
[["pat", re.compile("b")], ["repl", str], ["case", False], ["flags", 1]],
Expand Down