diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cd0714838a3f1..f6b497486c324 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -177,7 +177,7 @@ Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ - -- +- Bug in :meth:`DataFrame.rolling` not allowing for rolling over datetimes when ``axis=1`` (:issue: `28192`) - Bug in :meth:`DataFrame.groupby` not offering selection by column name when ``axis=1`` (:issue:`27614`) - Bug in :meth:`DataFrameGroupby.agg` not able to use lambda function with named aggregation (:issue:`27519`) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index a7e122fa3528f..29ef2e917ae57 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1653,7 +1653,10 @@ def is_datetimelike(self): def _on(self): if self.on is None: - return self.obj.index + if self.axis == 0: + return self.obj.index + elif self.axis == 1: + return self.obj.columns elif isinstance(self.obj, ABCDataFrame) and self.on in self.obj.columns: return Index(self.obj[self.on]) else: diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index b4787bf25e3bb..70ba85120af3c 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -334,3 +334,30 @@ def test_readonly_array(self): result = pd.Series(arr).rolling(2).mean() expected = pd.Series([np.nan, 2, np.nan, np.nan, 4]) tm.assert_series_equal(result, expected) + + def test_rolling_datetime(self, axis_frame, tz_naive_fixture): + # GH-28192 + tz = tz_naive_fixture + df = pd.DataFrame( + { + i: [1] * 2 + for i in pd.date_range("2019-8-01", "2019-08-03", freq="D", tz=tz) + } + ) + if axis_frame in [0, "index"]: + result = df.T.rolling("2D", axis=axis_frame).sum().T + else: + result = df.rolling("2D", axis=axis_frame).sum() + expected = pd.DataFrame( + { + **{ + i: [1.0] * 2 + for i in pd.date_range("2019-8-01", periods=1, freq="D", tz=tz) + }, + **{ + i: [2.0] * 2 + for i in pd.date_range("2019-8-02", "2019-8-03", freq="D", tz=tz) + }, + } + ) + tm.assert_frame_equal(result, expected)