Skip to content

BUG: fix rolling with centering and axis=1 (#46135) #46265

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 15 commits into from
May 6, 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,7 @@ Groupby/resample/rolling
- Bug in :meth:`Rolling.var` and :meth:`Rolling.std` would give non-zero result with window of same values (:issue:`42064`)
- Bug in :meth:`.Rolling.var` would segfault calculating weighted variance when window size was larger than data size (:issue:`46760`)
- Bug in :meth:`Grouper.__repr__` where ``dropna`` was not included. Now it is (:issue:`46754`)
- Bug in :meth:`DataFrame.rolling` gives ValueError when center=True, axis=1 and win_type is specified (:issue:`46135`)

Reshaping
^^^^^^^^^
Expand Down
6 changes: 1 addition & 5 deletions pandas/core/window/rolling.py
Original file line number Diff line number Diff line change
Expand Up @@ -1129,12 +1129,8 @@ def _center_window(self, result: np.ndarray, offset: int) -> np.ndarray:
"""
Center the result in the window for weighted rolling aggregations.
"""
if self.axis > result.ndim - 1:
raise ValueError("Requested axis is larger then no. of argument dimensions")

if offset > 0:
lead_indexer = [slice(None)] * result.ndim
lead_indexer[self.axis] = slice(offset, None)
lead_indexer = [slice(offset, None)]
result = np.copy(result[tuple(lead_indexer)])
return result

Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/window/test_win_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,3 +686,18 @@ def test_weighted_var_big_window_no_segfault(win_types, center):
expected = Series(np.NaN)

tm.assert_series_equal(result, expected)


@td.skip_if_no_scipy
def test_rolling_center_axis_1():
df = DataFrame(
{"a": [1, 1, 0, 0, 0, 1], "b": [1, 0, 0, 1, 0, 0], "c": [1, 0, 0, 1, 0, 1]}
)

result = df.rolling(window=3, axis=1, win_type="boxcar", center=True).sum()

expected = DataFrame(
{"a": [np.nan] * 6, "b": [3.0, 1.0, 0.0, 2.0, 0.0, 2.0], "c": [np.nan] * 6}
)

tm.assert_frame_equal(result, expected, check_dtype=True)