diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 931d18dc349f3..27d78d7c313c4 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -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 ^^^^^^^^^ diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 5006db44849e0..9617e27cc2e4b 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -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 diff --git a/pandas/tests/window/test_win_type.py b/pandas/tests/window/test_win_type.py index 11e288591fe75..8c8e9cadbfdc1 100644 --- a/pandas/tests/window/test_win_type.py +++ b/pandas/tests/window/test_win_type.py @@ -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)