Skip to content

Fix inconsistent casting to bool #28290

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 1 commit into from
Sep 5, 2019
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
10 changes: 8 additions & 2 deletions pandas/core/ops/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,13 @@ def na_op(x, y):
return result

fill_int = lambda x: x.fillna(0)
fill_bool = lambda x: x.fillna(False).astype(bool)

def fill_bool(x, left=None):
# if `left` is specifically not-boolean, we do not cast to bool
x = x.fillna(False)
if left is None or is_bool_dtype(left.dtype):
x = x.astype(bool)
return x

def wrapper(self, other):
is_self_int_dtype = is_integer_dtype(self.dtype)
Expand Down Expand Up @@ -835,7 +841,7 @@ def wrapper(self, other):

elif isinstance(other, (ABCSeries, ABCIndexClass)):
is_other_int_dtype = is_integer_dtype(other.dtype)
other = other if is_other_int_dtype else fill_bool(other)
other = other if is_other_int_dtype else fill_bool(other, self)

else:
# scalars, list, tuple, np.array
Expand Down
12 changes: 4 additions & 8 deletions pandas/tests/series/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,8 @@ def test_logical_operators_int_dtype_with_float(self):
s_0123 & [0.1, 4, 3.14, 2]
with pytest.raises(TypeError):
s_0123 & np.array([0.1, 4, 3.14, 2])

# FIXME: this should be consistent with the list case above
expected = Series([False, True, False, True])
result = s_0123 & Series([0.1, 4, -3.14, 2])
assert_series_equal(result, expected)
with pytest.raises(TypeError):
s_0123 & Series([0.1, 4, -3.14, 2])

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

s_abNd = Series(["a", "b", np.NaN, "d"])
result = s_0123 & s_abNd
expected = Series([False, True, False, True])
assert_series_equal(result, expected)
with pytest.raises(TypeError, match="unsupported.* 'int' and 'str'"):
s_0123 & s_abNd

def test_logical_operators_bool_dtype_with_int(self):
index = list("bca")
Expand Down