Skip to content

BUG: DatetimeIndexResamplerGroupby as_index interaction with .agg() #52819

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

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 9 additions & 1 deletion pandas/core/resample.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions pandas/tests/resample/test_resampler_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)