Skip to content

Bug groupby idxmin #25531

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 15 commits into from
Mar 30, 2019
Merged
7 changes: 5 additions & 2 deletions pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,11 @@ def _aggregate_item_by_item(self, func, *args, **kwargs):
data = obj[item]
colg = SeriesGroupBy(data, selection=item,
grouper=self.grouper)
result[item] = self._try_cast(
colg.aggregate(func, *args, **kwargs), data)

result[item] = colg.aggregate(func, *args, **kwargs)
if func != "idxmin" and func != "idxmax":
result[item] = self._try_cast(result[item], data)

except ValueError:
cannot_agg.append(item)
continue
Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/groupby/test_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,28 @@ def test_groupby_non_arithmetic_agg_int_like_precision(i):
assert res.iloc[0].b == data["expected"]


@pytest.mark.parametrize("func, expected", [
("idxmin", {'c_int': [0, 2], 'c_float': [1, 3], 'c_date': [1, 2]}),
("idxmax", {'c_int': [1, 3], 'c_float': [0, 2], 'c_date': [0, 3]})
])
def test_idxmin_idxmax_returns_int_types(func, expected):
# GH 25444
df = pd.DataFrame({'name': ['A', 'A', 'B', 'B'],
'c_int': [1, 2, 3, 4],
'c_float': [4.02, 3.03, 2.04, 1.05],
'c_date': ['2019', '2018', '2016', '2017']})
df['c_date'] = pd.to_datetime(df['c_date'])

result = getattr(df.groupby('name'), func)()

for col in result:
assert result[col].dtype == np.int64

df_expected = pd.DataFrame(expected, index=Index(['A', 'B'], name="name"))

tm.assert_frame_equal(result, df_expected)


def test_fill_consistency():

# GH9221
Expand Down