Skip to content

Commit 838c058

Browse files
committed
Fixed bug in df.resample using 'on' parameter
1 parent 238499a commit 838c058

File tree

3 files changed

+23
-4
lines changed

3 files changed

+23
-4
lines changed

doc/source/whatsnew/v0.23.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -515,7 +515,7 @@ Groupby/Resample/Rolling
515515
- Bug in :func:`DataFrame.resample` which silently ignored unsupported (or mistyped) options for ``label``, ``closed`` and ``convention`` (:issue:`19303`)
516516
- Bug in :func:`DataFrame.groupby` where tuples were interpreted as lists of keys rather than as keys (:issue:`17979`, :issue:`18249`)
517517
- Bug in ``transform`` where particular aggregation functions were being incorrectly cast to match the dtype(s) of the grouped data (:issue:`19200`)
518-
-
518+
- Bug in `DataFrame.groupby` with resample using `on` parameter when selecting column to apply function (:issue:`17813`)
519519

520520
Sparse
521521
^^^^^^

pandas/core/groupby.py

+13-3
Original file line numberDiff line numberDiff line change
@@ -423,6 +423,7 @@ def __init__(self, key=None, level=None, freq=None, axis=0, sort=False):
423423
self.obj = None
424424
self.indexer = None
425425
self.binner = None
426+
self._grouper = None
426427

427428
@property
428429
def ax(self):
@@ -465,12 +466,21 @@ def _set_grouper(self, obj, sort=False):
465466
raise ValueError(
466467
"The Grouper cannot specify both a key and a level!")
467468

469+
# Keep self.grouper value before overriding
470+
if self._grouper is None:
471+
self._grouper = self.grouper
472+
468473
# the key must be a valid info item
469474
if self.key is not None:
470475
key = self.key
471-
if key not in obj._info_axis:
472-
raise KeyError("The grouper name {0} is not found".format(key))
473-
ax = Index(obj[key], name=key)
476+
if getattr(self.grouper, 'name', None) == key and \
477+
isinstance(obj, Series):
478+
ax = self._grouper.take(obj.index)
479+
else:
480+
if key not in obj._info_axis:
481+
raise KeyError(
482+
"The grouper name {0} is not found".format(key))
483+
ax = Index(obj[key], name=key)
474484

475485
else:
476486
ax = obj._get_axis(self.axis)

pandas/tests/test_resample.py

+9
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,15 @@ def test_pipe(self):
252252
result = r.pipe(lambda x: x.max() - x.mean())
253253
tm.assert_frame_equal(result, expected)
254254

255+
def test_groupby_resample_on_api_with_getitem(self):
256+
# GH 17813
257+
df = pd.DataFrame({'id': list('aabbb'),
258+
'date': pd.date_range('1-1-2016', periods=5),
259+
'data': 1})
260+
exp = df.set_index('date').groupby('id').resample('2D')['data'].sum()
261+
result = df.groupby('id').resample('2D', on='date')['data'].sum()
262+
assert_series_equal(result, exp)
263+
255264
@td.skip_if_no_mpl
256265
def test_plot_api(self):
257266
# .resample(....).plot(...)

0 commit comments

Comments
 (0)