Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
5 changes: 4 additions & 1 deletion pandas/_libs/window/aggregations.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,10 @@ cdef inline void add_var(float64_t val, float64_t *nobs, float64_t *mean_x,
t = y - mean_x[0]
compensation[0] = t + mean_x[0] - y
delta = t
mean_x[0] = mean_x[0] + delta / nobs[0]
if nobs[0]:
mean_x[0] = mean_x[0] + delta / nobs[0]
else:
mean_x[0] = 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this zero? and not NaN

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume that if nobs is zero a new group starts, so I reset mean_x to zero. Analog to the initialization of mean_x in roll_var (compare with the initalization in line 349). However, I am not sure if this is correct.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Off the top of my head, this would also need testing when min_periods is 0 or len(array) as well to check if this is correct

ssqdm_x[0] = ssqdm_x[0] + (val - prev_mean) * (val - mean_x[0])


Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/window/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,6 +695,31 @@ def test_groupby_rolling_object_doesnt_affect_groupby_apply(self):
assert not g.mutated
assert not g.grouper.mutated

@pytest.mark.parametrize(
("window", "min_periods", "closed", "expected"),
[
(2, 0, "left", [None, 0.0, 1.0, 1.0, None, 0.0, 1.0, 1.0]),
(2, 2, "left", [None, None, 1.0, 1.0, None, None, 1.0, 1.0]),
(4, 4, "left", [None, None, None, None, None, None, None, None]),
(4, 4, "right", [None, None, None, 5.0, None, None, None, 5.0]),
],
)
def test_groupby_rolling_var(self, window, min_periods, closed, expected):
df = DataFrame([1, 2, 3, 4, 5, 6, 7, 8])
result = (
df.groupby([1, 2, 1, 2, 1, 2, 1, 2])
.rolling(window=window, min_periods=min_periods, closed=closed)
.var(0)
)
expected_result = DataFrame(
np.array(expected, dtype="float64"),
index=MultiIndex(
levels=[[1, 2], [0, 1, 2, 3, 4, 5, 6, 7]],
codes=[[0, 0, 0, 0, 1, 1, 1, 1], [0, 2, 4, 6, 1, 3, 5, 7]],
),
)
tm.assert_frame_equal(result, expected_result)

@pytest.mark.parametrize(
"columns", [MultiIndex.from_tuples([("A", ""), ("B", "C")]), ["A", "B"]]
)
Expand Down