Skip to content

BUG: Assigning boolean series with logical indexer #60127

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

6 changes: 6 additions & 0 deletions pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1918,7 +1918,13 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any:
# i.e. there are pd.NA elements
raise LossySetitemError
return element
# GH 57338
# Check boolean array set as object type
if tipo.kind == "O" and isinstance(element, np.ndarray):
if all(lib.is_bool(e) for e in element):
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if all(lib.is_bool(e) for e in element):
if lib.is_bool_array(element):

This could be faster.

return element.astype("bool")
raise LossySetitemError

if lib.is_bool(element):
return element
raise LossySetitemError
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/dtypes/cast/test_can_hold_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,17 @@ def test_can_hold_element_int8_int():
assert not can_hold_element(arr, np.uint32(element))
assert not can_hold_element(arr, np.int64(element))
assert not can_hold_element(arr, np.uint64(element))


def test_can_hold_element_bool():
arr = np.array([], dtype=bool)

element = True
assert can_hold_element(arr, element)
assert can_hold_element(arr, np.array([element]))
assert can_hold_element(arr, np.array([element], dtype=object))

element = 1
assert not can_hold_element(arr, element)
assert not can_hold_element(arr, np.array([element]))
assert not can_hold_element(arr, np.array([element], dtype=object))
Loading