Skip to content

Commit 7e68fe6

Browse files
mroeschkemeeseeksmachine
authored andcommitted
Backport PR pandas-dev#46065: BUG: groupby().rolling(freq) with monotonic dates within groups
1 parent 226f1c2 commit 7e68fe6

File tree

5 files changed

+96
-91
lines changed

5 files changed

+96
-91
lines changed

doc/source/whatsnew/v1.4.2.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Fixed regressions
2323

2424
Bug fixes
2525
~~~~~~~~~
26-
-
26+
- Bug in :meth:`Groupby.rolling` with a frequency window would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
2727
-
2828

2929
.. ---------------------------------------------------------------------------

pandas/core/window/rolling.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -837,7 +837,7 @@ def _gotitem(self, key, ndim, subset=None):
837837
subset = self.obj.set_index(self._on)
838838
return super()._gotitem(key, ndim, subset=subset)
839839

840-
def _validate_monotonic(self):
840+
def _validate_datetimelike_monotonic(self):
841841
"""
842842
Validate that "on" is monotonic; already validated at a higher level.
843843
"""
@@ -1687,7 +1687,7 @@ def _validate(self):
16871687
or isinstance(self._on, (DatetimeIndex, TimedeltaIndex, PeriodIndex))
16881688
) and isinstance(self.window, (str, BaseOffset, timedelta)):
16891689

1690-
self._validate_monotonic()
1690+
self._validate_datetimelike_monotonic()
16911691

16921692
# this will raise ValueError on non-fixed freqs
16931693
try:
@@ -1712,18 +1712,13 @@ def _validate(self):
17121712
elif not is_integer(self.window) or self.window < 0:
17131713
raise ValueError("window must be an integer 0 or greater")
17141714

1715-
def _validate_monotonic(self):
1715+
def _validate_datetimelike_monotonic(self):
17161716
"""
17171717
Validate monotonic (increasing or decreasing).
17181718
"""
17191719
if not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing):
1720-
self._raise_monotonic_error()
1721-
1722-
def _raise_monotonic_error(self):
1723-
formatted = self.on
1724-
if self.on is None:
1725-
formatted = "index"
1726-
raise ValueError(f"{formatted} must be monotonic")
1720+
on = "index" if self.on is None else self.on
1721+
raise ValueError(f"{on} must be monotonic.")
17271722

17281723
@doc(
17291724
_shared_docs["aggregate"],
@@ -2631,12 +2626,17 @@ def _get_window_indexer(self) -> GroupbyIndexer:
26312626
)
26322627
return window_indexer
26332628

2634-
def _validate_monotonic(self):
2629+
def _validate_datetimelike_monotonic(self):
26352630
"""
2636-
Validate that on is monotonic;
2631+
Validate that each group in self._on is monotonic
26372632
"""
2638-
if (
2639-
not (self._on.is_monotonic_increasing or self._on.is_monotonic_decreasing)
2640-
or self._on.hasnans
2641-
):
2642-
self._raise_monotonic_error()
2633+
# GH 46061
2634+
on = "index" if self.on is None else self.on
2635+
if self._on.hasnans:
2636+
raise ValueError(f"{on} must not have any NaT values.")
2637+
for group_indices in self._grouper.indices.values():
2638+
group_on = self._on.take(group_indices)
2639+
if not (
2640+
group_on.is_monotonic_increasing or group_on.is_monotonic_decreasing
2641+
):
2642+
raise ValueError(f"Each group within {on} must be monotonic.")

pandas/tests/window/test_groupby.py

+78-1
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ def test_groupby_rolling_nans_in_index(self, rollings, key):
651651
)
652652
if key == "index":
653653
df = df.set_index("a")
654-
with pytest.raises(ValueError, match=f"{key} must be monotonic"):
654+
with pytest.raises(ValueError, match=f"{key} must not have any NaT values"):
655655
df.groupby("c").rolling("60min", **rollings)
656656

657657
@pytest.mark.parametrize("group_keys", [True, False])
@@ -895,6 +895,83 @@ def test_nan_and_zero_endpoints(self):
895895
)
896896
tm.assert_series_equal(result, expected)
897897

898+
def test_groupby_rolling_non_monotonic(self):
899+
# GH 43909
900+
901+
shuffled = [3, 0, 1, 2]
902+
sec = 1_000
903+
df = DataFrame(
904+
[{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
905+
)
906+
with pytest.raises(ValueError, match=r".* must be monotonic"):
907+
df.groupby("c").rolling(on="t", window="3s")
908+
909+
def test_groupby_monotonic(self):
910+
911+
# GH 15130
912+
# we don't need to validate monotonicity when grouping
913+
914+
# GH 43909 we should raise an error here to match
915+
# behaviour of non-groupby rolling.
916+
917+
data = [
918+
["David", "1/1/2015", 100],
919+
["David", "1/5/2015", 500],
920+
["David", "5/30/2015", 50],
921+
["David", "7/25/2015", 50],
922+
["Ryan", "1/4/2014", 100],
923+
["Ryan", "1/19/2015", 500],
924+
["Ryan", "3/31/2016", 50],
925+
["Joe", "7/1/2015", 100],
926+
["Joe", "9/9/2015", 500],
927+
["Joe", "10/15/2015", 50],
928+
]
929+
930+
df = DataFrame(data=data, columns=["name", "date", "amount"])
931+
df["date"] = to_datetime(df["date"])
932+
df = df.sort_values("date")
933+
934+
expected = (
935+
df.set_index("date")
936+
.groupby("name")
937+
.apply(lambda x: x.rolling("180D")["amount"].sum())
938+
)
939+
result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
940+
tm.assert_series_equal(result, expected)
941+
942+
def test_datelike_on_monotonic_within_each_group(self):
943+
# GH 13966 (similar to #15130, closed by #15175)
944+
945+
# superseded by 43909
946+
# GH 46061: OK if the on is monotonic relative to each each group
947+
948+
dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
949+
df = DataFrame(
950+
{
951+
"A": [1] * 20 + [2] * 12 + [3] * 8,
952+
"B": np.concatenate((dates, dates)),
953+
"C": np.arange(40),
954+
}
955+
)
956+
957+
expected = (
958+
df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
959+
)
960+
result = df.groupby("A").rolling("4s", on="B").C.mean()
961+
tm.assert_series_equal(result, expected)
962+
963+
def test_datelike_on_not_monotonic_within_each_group(self):
964+
# GH 46061
965+
df = DataFrame(
966+
{
967+
"A": [1] * 3 + [2] * 3,
968+
"B": [Timestamp(year, 1, 1) for year in [2020, 2021, 2019]] * 2,
969+
"C": range(6),
970+
}
971+
)
972+
with pytest.raises(ValueError, match="Each group within B must be monotonic."):
973+
df.groupby("A").rolling("365D", on="B")
974+
898975

899976
class TestExpanding:
900977
def setup_method(self):

pandas/tests/window/test_rolling.py

-12
Original file line numberDiff line numberDiff line change
@@ -1419,18 +1419,6 @@ def test_groupby_rolling_nan_included():
14191419
tm.assert_frame_equal(result, expected)
14201420

14211421

1422-
def test_groupby_rolling_non_monotonic():
1423-
# GH 43909
1424-
1425-
shuffled = [3, 0, 1, 2]
1426-
sec = 1_000
1427-
df = DataFrame(
1428-
[{"t": Timestamp(2 * x * sec), "x": x + 1, "c": 42} for x in shuffled]
1429-
)
1430-
with pytest.raises(ValueError, match=r".* must be monotonic"):
1431-
df.groupby("c").rolling(on="t", window="3s")
1432-
1433-
14341422
@pytest.mark.parametrize("method", ["skew", "kurt"])
14351423
def test_rolling_skew_kurt_numerical_stability(method):
14361424
# GH#6929

pandas/tests/window/test_timeseries_window.py

-60
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
Series,
99
Timestamp,
1010
date_range,
11-
to_datetime,
1211
)
1312
import pandas._testing as tm
1413

@@ -643,65 +642,6 @@ def agg_by_day(x):
643642

644643
tm.assert_frame_equal(result, expected)
645644

646-
def test_groupby_monotonic(self):
647-
648-
# GH 15130
649-
# we don't need to validate monotonicity when grouping
650-
651-
# GH 43909 we should raise an error here to match
652-
# behaviour of non-groupby rolling.
653-
654-
data = [
655-
["David", "1/1/2015", 100],
656-
["David", "1/5/2015", 500],
657-
["David", "5/30/2015", 50],
658-
["David", "7/25/2015", 50],
659-
["Ryan", "1/4/2014", 100],
660-
["Ryan", "1/19/2015", 500],
661-
["Ryan", "3/31/2016", 50],
662-
["Joe", "7/1/2015", 100],
663-
["Joe", "9/9/2015", 500],
664-
["Joe", "10/15/2015", 50],
665-
]
666-
667-
df = DataFrame(data=data, columns=["name", "date", "amount"])
668-
df["date"] = to_datetime(df["date"])
669-
df = df.sort_values("date")
670-
671-
expected = (
672-
df.set_index("date")
673-
.groupby("name")
674-
.apply(lambda x: x.rolling("180D")["amount"].sum())
675-
)
676-
result = df.groupby("name").rolling("180D", on="date")["amount"].sum()
677-
tm.assert_series_equal(result, expected)
678-
679-
def test_non_monotonic_raises(self):
680-
# GH 13966 (similar to #15130, closed by #15175)
681-
682-
# superseded by 43909
683-
684-
dates = date_range(start="2016-01-01 09:30:00", periods=20, freq="s")
685-
df = DataFrame(
686-
{
687-
"A": [1] * 20 + [2] * 12 + [3] * 8,
688-
"B": np.concatenate((dates, dates)),
689-
"C": np.arange(40),
690-
}
691-
)
692-
693-
expected = (
694-
df.set_index("B").groupby("A").apply(lambda x: x.rolling("4s")["C"].mean())
695-
)
696-
with pytest.raises(ValueError, match=r".* must be monotonic"):
697-
df.groupby("A").rolling(
698-
"4s", on="B"
699-
).C.mean() # should raise for non-monotonic t series
700-
701-
df2 = df.sort_values("B")
702-
result = df2.groupby("A").rolling("4s", on="B").C.mean()
703-
tm.assert_series_equal(result, expected)
704-
705645
def test_rolling_cov_offset(self):
706646
# GH16058
707647

0 commit comments

Comments
 (0)