Skip to content

Commit 2a78acc

Browse files
rosagoldpalmb
andauthored
BUG: Fix for rolling with uneven nanosecond windows have wrong results (#43998)
* [FIX] for rolling with uneven nanoseconds have wrong results * Update indexers.pyx added issue number in comment Co-authored-by: Bert Palm <[email protected]>
1 parent 75be36e commit 2a78acc

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

doc/source/whatsnew/v1.4.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,7 @@ Groupby/resample/rolling
506506
- Bug in :meth:`GroupBy.apply` with time-based :class:`Grouper` objects incorrectly raising ``ValueError`` in corner cases where the grouping vector contains a ``NaT`` (:issue:`43500`, :issue:`43515`)
507507
- Bug in :meth:`GroupBy.mean` failing with ``complex`` dtype (:issue:`43701`)
508508
- Fixed bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` not calculating window bounds correctly for the first row when ``center=True`` and index is decreasing (:issue:`43927`)
509+
- Fixed bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` for centered datetimelike windows with uneven nanosecond (:issue:`43997`)
509510
- Bug in :meth:`GroupBy.nth` failing on ``axis=1`` (:issue:`43926`)
510511
- Fixed bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` not respecting right bound on centered datetime-like windows, if the index contain duplicates (:issue:`#3944`)
511512

pandas/_libs/window/indexers.pyx

+8
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,14 @@ def calculate_variable_window_bounds(
6262
if closed in ['left', 'both']:
6363
left_closed = True
6464

65+
# GH 43997:
66+
# If the forward and the backward facing windows
67+
# would result in a fraction of 1/2 a nanosecond
68+
# we need to make both interval ends inclusive.
69+
if center and window_size % 2 == 1:
70+
right_closed = True
71+
left_closed = True
72+
6573
if index[num_values - 1] < index[0]:
6674
index_growth_sign = -1
6775

pandas/tests/window/test_rolling.py

+17
Original file line numberDiff line numberDiff line change
@@ -1276,6 +1276,23 @@ def test_rolling_decreasing_indices_centered(window, closed, expected, frame_or_
12761276
tm.assert_equal(result_dec, expected_dec)
12771277

12781278

1279+
@pytest.mark.parametrize(
1280+
"window,expected",
1281+
[
1282+
("1ns", [1.0, 1.0, 1.0, 1.0]),
1283+
("3ns", [2.0, 3.0, 3.0, 2.0]),
1284+
],
1285+
)
1286+
def test_rolling_center_nanosecond_resolution(
1287+
window, closed, expected, frame_or_series
1288+
):
1289+
index = date_range("2020", periods=4, freq="1ns")
1290+
df = frame_or_series([1, 1, 1, 1], index=index, dtype=float)
1291+
expected = frame_or_series(expected, index=index, dtype=float)
1292+
result = df.rolling(window, closed=closed, center=True).sum()
1293+
tm.assert_equal(result, expected)
1294+
1295+
12791296
@pytest.mark.parametrize(
12801297
"method,expected",
12811298
[

0 commit comments

Comments
 (0)