Skip to content

Commit d3b1c7e

Browse files
jbrockmendelproost
authored andcommitted
Fix inconsistent casting to bool (pandas-dev#28290)
1 parent 220ffd3 commit d3b1c7e

File tree

2 files changed

+12
-10
lines changed

2 files changed

+12
-10
lines changed

pandas/core/ops/__init__.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -806,7 +806,13 @@ def na_op(x, y):
806806
return result
807807

808808
fill_int = lambda x: x.fillna(0)
809-
fill_bool = lambda x: x.fillna(False).astype(bool)
809+
810+
def fill_bool(x, left=None):
811+
# if `left` is specifically not-boolean, we do not cast to bool
812+
x = x.fillna(False)
813+
if left is None or is_bool_dtype(left.dtype):
814+
x = x.astype(bool)
815+
return x
810816

811817
def wrapper(self, other):
812818
is_self_int_dtype = is_integer_dtype(self.dtype)
@@ -835,7 +841,7 @@ def wrapper(self, other):
835841

836842
elif isinstance(other, (ABCSeries, ABCIndexClass)):
837843
is_other_int_dtype = is_integer_dtype(other.dtype)
838-
other = other if is_other_int_dtype else fill_bool(other)
844+
other = other if is_other_int_dtype else fill_bool(other, self)
839845

840846
else:
841847
# scalars, list, tuple, np.array

pandas/tests/series/test_operators.py

+4-8
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,8 @@ def test_logical_operators_int_dtype_with_float(self):
103103
s_0123 & [0.1, 4, 3.14, 2]
104104
with pytest.raises(TypeError):
105105
s_0123 & np.array([0.1, 4, 3.14, 2])
106-
107-
# FIXME: this should be consistent with the list case above
108-
expected = Series([False, True, False, True])
109-
result = s_0123 & Series([0.1, 4, -3.14, 2])
110-
assert_series_equal(result, expected)
106+
with pytest.raises(TypeError):
107+
s_0123 & Series([0.1, 4, -3.14, 2])
111108

112109
def test_logical_operators_int_dtype_with_str(self):
113110
s_1111 = Series([1] * 4, dtype="int8")
@@ -145,9 +142,8 @@ def test_logical_operators_int_dtype_with_object(self):
145142
assert_series_equal(result, expected)
146143

147144
s_abNd = Series(["a", "b", np.NaN, "d"])
148-
result = s_0123 & s_abNd
149-
expected = Series([False, True, False, True])
150-
assert_series_equal(result, expected)
145+
with pytest.raises(TypeError, match="unsupported.* 'int' and 'str'"):
146+
s_0123 & s_abNd
151147

152148
def test_logical_operators_bool_dtype_with_int(self):
153149
index = list("bca")

0 commit comments

Comments
 (0)