Skip to content

Fix groupby-resample KeyError when resampling on Index and giving explicit list of columns. (1.5.x) #50841

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 4 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/v1.5.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Bug fixes
- Fixed bug when instantiating a :class:`DataFrame` subclass inheriting from ``typing.Generic`` that triggered a ``UserWarning`` on python 3.11 (:issue:`49649`)
- Bug in :func:`pivot_table` with NumPy 1.24 or greater when the :class:`DataFrame` columns has nested elements (:issue:`50342`)
- Bug in :func:`pandas.testing.assert_series_equal` (and equivalent ``assert_`` functions) when having nested data and using numpy >= 1.25 (:issue:`50360`)
- Bug in :meth:`DataFrameGroupBy.resample` raises ``KeyError`` when getting the result from a key list when resampling on time index (:issue:`50840`)

.. ---------------------------------------------------------------------------
.. _whatsnew_153.other:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -1238,7 +1238,7 @@ def _gotitem(self, key, ndim, subset=None):

# Try to select from a DataFrame, falling back to a Series
try:
if isinstance(key, list) and self.key not in key:
if isinstance(key, list) and self.key not in key and self.key is not None:
key.append(self.key)
groupby = self._groupby[key]
except IndexError:
Expand Down
30 changes: 30 additions & 0 deletions pandas/tests/resample/test_resampler_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,3 +497,33 @@ def test_groupby_resample_with_list_of_keys():
),
)
tm.assert_frame_equal(result, expected)


def test_groupby_resample_on_index_with_list_of_keys():
# GH 47362
df = DataFrame(
data={
"group": [0, 0, 0, 0, 1, 1, 1, 1],
"val": [3, 1, 4, 1, 5, 9, 2, 6],
},
index=Series(
date_range(start="2016-01-01", periods=8),
name="date",
),
)
result = df.groupby("group").resample("2D")[["val"]].mean()
expected = DataFrame(
data={
"val": [2.0, 2.5, 7.0, 4.0],
},
index=Index(
data=[
(0, Timestamp("2016-01-01")),
(0, Timestamp("2016-01-03")),
(1, Timestamp("2016-01-05")),
(1, Timestamp("2016-01-07")),
],
name=("group", "date"),
),
)
tm.assert_frame_equal(result, expected)