Skip to content

Commit

Permalink
cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
rhshadrach committed Sep 24, 2023
1 parent 1325855 commit e2dd88a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
10 changes: 7 additions & 3 deletions pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -5763,9 +5763,13 @@ def _idxmax_idxmin(
expected_len = np.prod(
[len(ping.group_index) for ping in self.grouper.groupings]
)
assert len(self.grouper.result_index) <= expected_len
if len(self.grouper.groupings) == 1:
result_len = len(self.grouper.groupings[0].grouping_vector.unique())
else:
result_len = len(self.grouper.result_index)
assert result_len <= expected_len
# result_index only contains observed groups
has_unobserved = len(self.grouper.result_index) < expected_len
has_unobserved = result_len < expected_len
raise_err = not ignore_unobserved and has_unobserved
else:
raise_err = False
Expand Down Expand Up @@ -5794,7 +5798,7 @@ def func(df):
raise ValueError(
f"Can't get {how} of an empty group due to unobserved categories. "
"Specify observed=True in groupby instead."
)
) from None
raise

result = result.astype(self.obj.index.dtype) if result.empty else result
Expand Down
5 changes: 5 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2068,6 +2068,11 @@ def get_categorical_invalid_expected():
result = get_result(numeric_only=True)
expected = get_categorical_invalid_expected()
tm.assert_equal(result, expected)
elif op in ["idxmin", "idxmax"] and isinstance(columns, list):
with pytest.raises(
ValueError, match="empty group due to unobserved categories"
):
get_result(numeric_only=True)
return

if op in ["prod", "sum", "skew"]:
Expand Down

0 comments on commit e2dd88a

Please sign in to comment.