Skip to content

Bug: Resample ignoring closed=right for TimedeltaIndex #45539

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

Merged
merged 2 commits into from
Jan 22, 2022
Merged
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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ Plotting

Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
-
- Bug in :meth:`DataFrame.resample` ignoring ``closed="right"`` on :class:`TimedeltaIndex` (:issue:`45414`)
-

Reshaping
Expand Down
11 changes: 9 additions & 2 deletions pandas/core/resample.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/resample/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)