Skip to content

Commit 641ebf4

Browse files
authored
BUG: StringArray * bools (#62706)
1 parent 9ffdf03 commit 641ebf4

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1013,6 +1013,7 @@ Strings
10131013
^^^^^^^
10141014
- Bug in :meth:`Series.str.zfill` raising ``AttributeError`` for :class:`ArrowDtype` (:issue:`61485`)
10151015
- Bug in :meth:`Series.value_counts` would not respect ``sort=False`` for series having ``string`` dtype (:issue:`55224`)
1016+
- Bug in multiplication with a :class:`StringDtype` incorrectly allowing multiplying by bools; explicitly cast to integers instead (:issue:`62595`)
10161017

10171018
Interval
10181019
^^^^^^^^

pandas/core/arrays/string_.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,6 +1113,16 @@ def _cmp_method(self, other, op):
11131113
other = np.asarray(other)
11141114
other = other[valid]
11151115

1116+
other_dtype = getattr(other, "dtype", None)
1117+
if op.__name__.strip("_") in ["mul", "rmul"] and (
1118+
lib.is_bool(other) or lib.is_np_dtype(other_dtype, "b")
1119+
):
1120+
# GH#62595
1121+
raise TypeError(
1122+
"Cannot multiply StringArray by bools. "
1123+
"Explicitly cast to integers instead."
1124+
)
1125+
11161126
if op.__name__ in ops.ARITHMETIC_BINOPS:
11171127
result = np.empty_like(self._ndarray, dtype="object")
11181128
result[mask] = self.dtype.na_value

pandas/tests/arithmetic/test_string.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,25 @@ def test_pyarrow_numpy_string_invalid():
112112

113113
with pytest.raises(TypeError, match="Invalid comparison"):
114114
ser > ser4
115+
116+
117+
def test_mul_bool_invalid(any_string_dtype):
118+
# GH#62595
119+
dtype = any_string_dtype
120+
ser = Series(["a", "b", "c"], dtype=dtype)
121+
122+
if dtype == object:
123+
pytest.skip("This is not expect to raise")
124+
elif dtype.storage == "python":
125+
msg = "Cannot multiply StringArray by bools. Explicitly cast to integers"
126+
else:
127+
msg = "Can only string multiply by an integer"
128+
129+
with pytest.raises(TypeError, match=msg):
130+
False * ser
131+
with pytest.raises(TypeError, match=msg):
132+
ser * True
133+
with pytest.raises(TypeError, match=msg):
134+
ser * np.array([True, False, True], dtype=bool)
135+
with pytest.raises(TypeError, match=msg):
136+
np.array([True, False, True], dtype=bool) * ser

0 commit comments

Comments
 (0)