Skip to content

Commit 7b77ce1

Browse files
committed
BUG: groupby.idxmin/idxmax with all NA values should raise
1 parent faf3bbb commit 7b77ce1

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

pandas/_libs/groupby.pyx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2048,9 +2048,8 @@ def group_idxmin_idxmax(
20482048
group_min_or_max = np.empty_like(out, dtype=values.dtype)
20492049
seen = np.zeros_like(out, dtype=np.uint8)
20502050

2051-
# When using transform, we need a valid value for take in the case
2052-
# a category is not observed; these values will be dropped
2053-
out[:] = 0
2051+
# Sentinel for no valid values.
2052+
out[:] = -1
20542053

20552054
with nogil(numeric_object_t is not object):
20562055
for i in range(N):

pandas/core/groupby/groupby.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1784,7 +1784,7 @@ def array_func(values: ArrayLike) -> ArrayLike:
17841784
new_mgr = data.grouped_reduce(array_func)
17851785
res = self._wrap_agged_manager(new_mgr)
17861786
if how in ["idxmin", "idxmax"]:
1787-
res = self._wrap_idxmax_idxmin(res)
1787+
res = self._wrap_idxmax_idxmin(res, how=how, skipna=kwargs["skipna"])
17881788
out = self._wrap_aggregated_output(res)
17891789
return out
17901790

@@ -5715,10 +5715,17 @@ def _idxmax_idxmin(
57155715
)
57165716
return result
57175717

5718-
def _wrap_idxmax_idxmin(self, res: NDFrameT) -> NDFrameT:
5718+
def _wrap_idxmax_idxmin(
5719+
self, res: NDFrameT, how: Literal["idxmax", "idxmin"], skipna: bool
5720+
) -> NDFrameT:
57195721
index = self.obj.index
57205722
if res.size == 0:
57215723
result = res.astype(index.dtype)
5724+
elif skipna and res.lt(0).any(axis=None):
5725+
raise ValueError(
5726+
f"{type(self).__name__}.{how} with skipna=True encountered all NA "
5727+
f"value in a group."
5728+
)
57225729
else:
57235730
if isinstance(index, MultiIndex):
57245731
index = index.to_flat_index()

0 commit comments

Comments
 (0)