diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 1ae76984484af..9756ae7adf930 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -241,7 +241,7 @@ Plotting Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ -- +- Bug in :meth:`DataFrame.resample` ignoring ``closed="right"`` on :class:`TimedeltaIndex` (:issue:`45414`) - Reshaping diff --git a/pandas/core/resample.py b/pandas/core/resample.py index e0b9eac618bc9..53d75255da536 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1702,12 +1702,19 @@ def _get_time_delta_bins(self, ax: TimedeltaIndex): return binner, [], labels start, end = ax.min(), ax.max() + + if self.closed == "right": + end += self.freq + labels = binner = timedelta_range( start=start, end=end, freq=self.freq, name=ax.name ) - end_stamps = labels + self.freq - bins = ax.searchsorted(end_stamps, side="left") + end_stamps = labels + if self.closed == "left": + end_stamps += self.freq + + bins = ax.searchsorted(end_stamps, side=self.closed) if self.offset: # GH 10530 & 31809 diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index d55dbfca9ebdf..ad1c361373189 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -191,3 +191,17 @@ def test_resample_quantile_timedelta(): index=pd.date_range("20200101", periods=2, tz="UTC", freq="2D"), ) tm.assert_frame_equal(result, expected) + + +def test_resample_closed_right(): + # GH#45414 + idx = pd.Index([pd.Timedelta(seconds=120 + i * 30) for i in range(10)]) + ser = Series(range(10), index=idx) + result = ser.resample("T", closed="right", label="right").sum() + expected = Series( + [0, 3, 7, 11, 15, 9], + index=pd.TimedeltaIndex( + [pd.Timedelta(seconds=120 + i * 60) for i in range(6)], freq="T" + ), + ) + tm.assert_series_equal(result, expected)