diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 56284ba9a9ebf..5c901e1e54d63 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -370,6 +370,7 @@ Missing MultiIndex ^^^^^^^^^^ - Bug in :meth:`DataFrame.__getitem__` not preserving dtypes for :class:`MultiIndex` partial keys (:issue:`51895`) +- Bug in :meth:`DatetimeIndexResamplerGroupby.agg({})`, where the aggregatio function wouldn't work if :class:`DatetimeIndexResamplerGroupby` was created from :class:`Groupby` w. ``as_index=False`` (:issue:`52819`) - Bug in :meth:`MultiIndex.set_levels` not preserving dtypes for :class:`Categorical` (:issue:`52125`) I/O diff --git a/pandas/core/resample.py b/pandas/core/resample.py index f8adb2332609b..836461c5a644e 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1,10 +1,12 @@ from __future__ import annotations +from contextlib import nullcontext import copy from textwrap import dedent from typing import ( TYPE_CHECKING, Callable, + ContextManager, Hashable, Literal, cast, @@ -327,7 +329,13 @@ def pipe( axis="", ) def aggregate(self, func=None, *args, **kwargs): - result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() + context_manager: ContextManager + if isinstance(self, DatetimeIndexResamplerGroupby): + context_manager = com.temp_setattr(self._groupby, "as_index", True) + else: + context_manager = nullcontext() + with context_manager: + result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: how = func result = self._groupby_and_aggregate(how, *args, **kwargs) diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index 1682edb42915d..1c14ad8e8f8b3 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -659,3 +659,29 @@ def test_groupby_resample_on_index_with_list_of_keys_missing_column(): ) with pytest.raises(KeyError, match="Columns not found"): df.groupby("group").resample("2D")[["val_not_in_dataframe"]].mean() + + +def test_groupby_resample_agg_dict_works_for_as_index_false(): + # GH 52397 + expected = ( + DataFrame( + {"a": np.repeat([0, 1, 2, 3, 4], 2), "b": range(50, 60)}, + index=date_range(start=Timestamp.now(), freq="1min", periods=10), + ) + .groupby("a", as_index=True) + .resample("2min") + .min() + ) + expected.drop(columns=["a"], inplace=True) + + result = ( + DataFrame( + {"a": np.repeat([0, 1, 2, 3, 4], 2), "b": range(50, 60)}, + index=date_range(start=Timestamp.now(), freq="1min", periods=10), + ) + .groupby("a", as_index=False) + .resample("2min") + .agg({"b": "min"}) + ) + + tm.assert_frame_equal(expected, result)