Skip to content

Commit f943864

Browse files
authored
BUG: Fix GroupBy.idxmin/idxmax retrun wrong type on empty (#51423)
1 parent efe896c commit f943864

File tree

3 files changed

+7
-5
lines changed

3 files changed

+7
-5
lines changed

doc/source/whatsnew/v2.1.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ Plotting
183183

184184
Groupby/resample/rolling
185185
^^^^^^^^^^^^^^^^^^^^^^^^
186-
-
186+
- 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`)
187187
-
188188

189189
Reshaping

pandas/core/groupby/generic.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,12 +1084,12 @@ def nsmallest(
10841084
@doc(Series.idxmin.__doc__)
10851085
def idxmin(self, axis: Axis = 0, skipna: bool = True) -> Series:
10861086
result = self._op_via_apply("idxmin", axis=axis, skipna=skipna)
1087-
return result
1087+
return result.astype(self.obj.index.dtype) if result.empty else result
10881088

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

10941094
@doc(Series.corr.__doc__)
10951095
def corr(
@@ -2012,7 +2012,7 @@ def func(df):
20122012
result = self._python_apply_general(
20132013
func, self._obj_with_exclusions, not_indexed_same=True
20142014
)
2015-
return result
2015+
return result.astype(self.obj.index.dtype) if result.empty else result
20162016

20172017
def idxmin(
20182018
self,
@@ -2098,7 +2098,7 @@ def func(df):
20982098
result = self._python_apply_general(
20992099
func, self._obj_with_exclusions, not_indexed_same=True
21002100
)
2101-
return result
2101+
return result.astype(self.obj.index.dtype) if result.empty else result
21022102

21032103
boxplot = boxplot_frame_groupby
21042104

pandas/tests/groupby/test_groupby.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1984,6 +1984,8 @@ def get_categorical_invalid_expected():
19841984

19851985
result = get_result()
19861986
expected = df.set_index(keys)[columns]
1987+
if op in ["idxmax", "idxmin"]:
1988+
expected = expected.astype(df.index.dtype)
19871989
if override_dtype is not None:
19881990
expected = expected.astype(override_dtype)
19891991
if len(keys) == 1:

0 commit comments

Comments
 (0)