Skip to content

BUG: Fix GroupBy.idxmin/idxmax retrun wrong type on empty #51423

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 16 commits into from
Feb 25, 2023
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
-
- Bug in :meth:`DataFrameGroupBy.idxmin`, :meth:`SeriesGroupBy.idxmin`, :meth:`DataFrameGroupBy.idxmax`, :meth:`SeriesGroupBy.idxmax` return wrong dtype when used on empty DataFrameGroupBy or SeriesGroupBy (:issue:`51423`)
-

Reshaping
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1084,12 +1084,12 @@ def nsmallest(
@doc(Series.idxmin.__doc__)
def idxmin(self, axis: Axis = 0, skipna: bool = True) -> Series:
result = self._op_via_apply("idxmin", axis=axis, skipna=skipna)
return result
return result.astype(self.obj.index.dtype) if result.empty else result

@doc(Series.idxmax.__doc__)
def idxmax(self, axis: Axis = 0, skipna: bool = True) -> Series:
result = self._op_via_apply("idxmax", axis=axis, skipna=skipna)
return result
return result.astype(self.obj.index.dtype) if result.empty else result

@doc(Series.corr.__doc__)
def corr(
Expand Down Expand Up @@ -2018,7 +2018,7 @@ def func(df):
result = self._python_apply_general(
func, self._obj_with_exclusions, not_indexed_same=True
)
return result
return result.astype(self.obj.index.dtype) if result.empty else result

def idxmin(
self,
Expand Down Expand Up @@ -2104,7 +2104,7 @@ def func(df):
result = self._python_apply_general(
func, self._obj_with_exclusions, not_indexed_same=True
)
return result
return result.astype(self.obj.index.dtype) if result.empty else result

boxplot = boxplot_frame_groupby

Expand Down
2 changes: 2 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -1984,6 +1984,8 @@ def get_categorical_invalid_expected():

result = get_result()
expected = df.set_index(keys)[columns]
if op in ["idxmax", "idxmin"]:
expected = expected.astype(df.index.dtype)
if override_dtype is not None:
expected = expected.astype(override_dtype)
if len(keys) == 1:
Expand Down