diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 2b8ed3c97d026..24ac7c040a45d 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -2513,8 +2513,9 @@ def _get_window_indexer(self) -> GroupbyIndexer: def _validate_monotonic(self): """ Validate that on is monotonic; - in this case we have to check only for nans, because - monotonicity was already validated at a higher level. """ - if self._on.hasnans: + if ( + not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing) + or self._on.hasnans + ): self._raise_monotonic_error() diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index d58eeaa7cbcb1..0391dc56c5791 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1417,6 +1417,17 @@ def test_groupby_rolling_nan_included(): tm.assert_frame_equal(result, expected) +def test_groupby_rolling_non_monotonic(): + # GH 43909 + shuffled = [3, 0, 1, 2] + sec = 1_000_000_000 + df = DataFrame( + [{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled] + ) + with pytest.raises(ValueError, match=r".* must be monotonic"): + df.groupby("c").rolling(on="t", window="3s") + + @pytest.mark.parametrize("method", ["skew", "kurt"]) def test_rolling_skew_kurt_numerical_stability(method): # GH#6929