Skip to content

Commit 416e622

Browse files
Backport PR pandas-dev#45274: Fix groupby any/all on an empty series/frame (pandas-dev#45297)
Co-authored-by: Richard Shadrach <[email protected]>
1 parent 2f090a5 commit 416e622

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

pandas/core/groupby/groupby.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1750,7 +1750,9 @@ def objs_to_bool(vals: ArrayLike) -> tuple[np.ndarray, type]:
17501750
if is_object_dtype(vals.dtype):
17511751
# GH#37501: don't raise on pd.NA when skipna=True
17521752
if skipna:
1753-
func = np.vectorize(lambda x: bool(x) if not isna(x) else True)
1753+
func = np.vectorize(
1754+
lambda x: bool(x) if not isna(x) else True, otypes=[bool]
1755+
)
17541756
vals = func(vals)
17551757
else:
17561758
vals = vals.astype(bool, copy=False)

pandas/tests/groupby/test_any_all.py

+10
Original file line numberDiff line numberDiff line change
@@ -178,3 +178,13 @@ def test_object_NA_raises_with_skipna_false(bool_agg_func):
178178
ser = Series([pd.NA], dtype=object)
179179
with pytest.raises(TypeError, match="boolean value of NA is ambiguous"):
180180
ser.groupby([1]).agg(bool_agg_func, skipna=False)
181+
182+
183+
@pytest.mark.parametrize("bool_agg_func", ["any", "all"])
184+
def test_empty(frame_or_series, bool_agg_func):
185+
# GH 45231
186+
kwargs = {"columns": ["a"]} if frame_or_series is DataFrame else {"name": "a"}
187+
obj = frame_or_series(**kwargs, dtype=object)
188+
result = getattr(obj.groupby(obj.index), bool_agg_func)()
189+
expected = frame_or_series(**kwargs, dtype=bool)
190+
tm.assert_equal(result, expected)

0 commit comments

Comments
 (0)