Skip to content

Commit 0e6ccaf

Browse files
kristopheryahookeitakurita
authored andcommitted
BUG: Incorrect handling of rolling.cov with offset window
1 parent d50f981 commit 0e6ccaf

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v0.20.2.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ Plotting
6060
Groupby/Resample/Rolling
6161
^^^^^^^^^^^^^^^^^^^^^^^^
6262

63-
63+
- Bug in ``rolling.cov()`` with offset window (:issue:`16058`)
6464

6565

6666
Sparse

pandas/core/window.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ def __init__(self, obj, window=None, min_periods=None, freq=None,
8181
self.freq = freq
8282
self.center = center
8383
self.win_type = win_type
84+
self.win_freq = None
8485
self.axis = obj._get_axis_number(axis) if axis is not None else None
8586
self.validate()
8687

@@ -996,7 +997,10 @@ def cov(self, other=None, pairwise=None, ddof=1, **kwargs):
996997
# only default unset
997998
pairwise = True if pairwise is None else pairwise
998999
other = self._shallow_copy(other)
999-
window = self._get_window(other)
1000+
if self.is_freq_type:
1001+
window = self.win_freq
1002+
else:
1003+
window = self._get_window(other)
10001004

10011005
def _get_cov(X, Y):
10021006
# GH #12373 : rolling functions error on float32 data
@@ -1088,6 +1092,7 @@ def validate(self):
10881092
"based windows")
10891093

10901094
# this will raise ValueError on non-fixed freqs
1095+
self.win_freq = self.window
10911096
self.window = freq.nanos
10921097
self.win_type = 'freq'
10931098

pandas/tests/test_window.py

+16
Original file line numberDiff line numberDiff line change
@@ -3801,3 +3801,19 @@ def test_non_monotonic(self):
38013801
df2 = df.sort_values('B')
38023802
result = df2.groupby('A').rolling('4s', on='B').C.mean()
38033803
tm.assert_series_equal(result, expected)
3804+
3805+
def test_rolling_cov_offset(self):
3806+
# GH16058
3807+
3808+
idx = pd.date_range('2017-01-01', periods=24, freq='1h')
3809+
ss = pd.Series(np.arange(len(idx)), index=idx)
3810+
3811+
result = ss.rolling('2h').cov()
3812+
expected = pd.Series([np.nan] + [0.5 for _ in range(len(idx) - 1)],
3813+
index=idx)
3814+
tm.assert_series_equal(result, expected)
3815+
3816+
result = ss.rolling('3h').cov()
3817+
expected = pd.Series([np.nan, 0.5] + [1.0 for _ in range(len(idx) - 2)],
3818+
index=idx)
3819+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)