Skip to content

[backport 2.3.x] BUG/DEPR: logical operation with bool and string (#61995) #62114

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 5 commits into from
Aug 19, 2025
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.3.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Bug fixes
- Fix :meth:`~DataFrame.to_json` with ``orient="table"`` to correctly use the
"string" type in the JSON Table Schema for :class:`StringDtype` columns
(:issue:`61889`)
- Boolean operations (``|``, ``&``, ``^``) with bool-dtype objects on the left and :class:`StringDtype` objects on the right now cast the string to bool, with a deprecation warning (:issue:`60234`)
- Fixed ``~Series.str.match``, ``~Series.str.fullmatch`` and ``~Series.str.contains``
with compiled regex for the Arrow-backed string dtype (:issue:`61964`, :issue:`61942`)

Expand Down
19 changes: 19 additions & 0 deletions pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,25 @@ def _logical_method(self, other, op):
# integer types. Otherwise these are boolean ops.
if pa.types.is_integer(self._pa_array.type):
return self._evaluate_op_method(other, op, ARROW_BIT_WISE_FUNCS)
elif (
(
pa.types.is_string(self._pa_array.type)
or pa.types.is_large_string(self._pa_array.type)
)
and op in (roperator.ror_, roperator.rand_, roperator.rxor)
and isinstance(other, np.ndarray)
and other.dtype == bool
):
# GH#60234 backward compatibility for the move to StringDtype in 3.0
op_name = op.__name__[1:].strip("_")
warnings.warn(
f"'{op_name}' operations between boolean dtype and {self.dtype} are "
"deprecated and will raise in a future version. Explicitly "
"cast the strings to a boolean dtype before operating instead.",
DeprecationWarning,
stacklevel=find_stack_level(),
)
return op(other, self.astype(bool))
else:
return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS)

Expand Down
21 changes: 21 additions & 0 deletions pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
missing,
nanops,
ops,
roperator,
)
from pandas.core.algorithms import isin
from pandas.core.array_algos import masked_reductions
Expand Down Expand Up @@ -385,6 +386,26 @@ class BaseStringArray(ExtensionArray):

dtype: StringDtype

# TODO(4.0): Once the deprecation here is enforced, this method can be
# removed and we use the parent class method instead.
def _logical_method(self, other, op):
if (
op in (roperator.ror_, roperator.rand_, roperator.rxor)
and isinstance(other, np.ndarray)
and other.dtype == bool
):
# GH#60234 backward compatibility for the move to StringDtype in 3.0
op_name = op.__name__[1:].strip("_")
warnings.warn(
f"'{op_name}' operations between boolean dtype and {self.dtype} are "
"deprecated and will raise in a future version. Explicitly "
"cast the strings to a boolean dtype before operating instead.",
DeprecationWarning,
stacklevel=find_stack_level(),
)
return op(other, self.astype(bool))
return NotImplemented

@doc(ExtensionArray.tolist)
def tolist(self):
if self.ndim > 1:
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/strings/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -776,3 +776,27 @@ def test_series_str_decode():
result = Series([b"x", b"y"]).str.decode(encoding="UTF-8", errors="strict")
expected = Series(["x", "y"], dtype="str")
tm.assert_series_equal(result, expected)


def test_reversed_logical_ops(any_string_dtype):
# GH#60234
dtype = any_string_dtype
warn = None if dtype == object else DeprecationWarning
left = Series([True, False, False, True])
right = Series(["", "", "b", "c"], dtype=dtype)

msg = "operations between boolean dtype and"
with tm.assert_produces_warning(warn, match=msg):
result = left | right
expected = left | right.astype(bool)
tm.assert_series_equal(result, expected)

with tm.assert_produces_warning(warn, match=msg):
result = left & right
expected = left & right.astype(bool)
tm.assert_series_equal(result, expected)

with tm.assert_produces_warning(warn, match=msg):
result = left ^ right
expected = left ^ right.astype(bool)
tm.assert_series_equal(result, expected)
Loading