Skip to content

Commit 8469157

Browse files
mroeschkesimonjayhawkins
authored andcommitted
BUG: groupby().rolling(freq) with monotonic dates within groups pandas-dev#46065 (pandas-dev#46567)
(cherry picked from commit d2aa44f)
1 parent dc48dc9 commit 8469157

File tree

5 files changed

+96
-72
lines changed

5 files changed

+96
-72
lines changed

doc/source/whatsnew/v1.4.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ Bug fixes
3333
- Fixed "longtable" formatting in :meth:`.Styler.to_latex` when ``column_format`` is given in extended format (:issue:`46037`)
3434
- Fixed incorrect rendering in :meth:`.Styler.format` with ``hyperlinks="html"`` when the url contains a colon or other special characters (:issue:`46389`)
3535
- Improved error message in :class:`~pandas.core.window.Rolling` when ``window`` is a frequency and ``NaT`` is in the rolling axis (:issue:`46087`)
36+
- Fixed :meth:`Groupby.rolling` with a frequency window that would raise a ``ValueError`` even if the datetimes within each group were monotonic (:issue:`46061`)
3637

3738
.. ---------------------------------------------------------------------------
3839

pandas/core/window/rolling.py

+18
Original file line numberDiff line numberDiff line change
@@ -2630,3 +2630,21 @@ def _get_window_indexer(self) -> GroupbyIndexer:
26302630
indexer_kwargs=indexer_kwargs,
26312631
)
26322632
return window_indexer
2633+
2634+
def _validate_datetimelike_monotonic(self):
2635+
"""
2636+
Validate that each group in self._on is monotonic
2637+
"""
2638+
# GH 46061
2639+
if self._on.hasnans:
2640+
self._raise_monotonic_error("values must not have NaT")
2641+
for group_indices in self._grouper.indices.values():
2642+
group_on = self._on.take(group_indices)
2643+
if not (
2644+
group_on.is_monotonic_increasing or group_on.is_monotonic_decreasing
2645+
):
2646+
on = "index" if self.on is None else self.on
2647+
raise ValueError(
2648+
f"Each group within {on} must be monotonic. "
2649+
f"Sort the values in {on} first."
2650+
)

pandas/tests/window/test_groupby.py

+77
Original file line numberDiff line numberDiff line change
@@ -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
@@ -9,7 +9,6 @@
99
Series,
1010
Timestamp,
1111
date_range,
12-
to_datetime,
1312
)
1413
import pandas._testing as tm
1514

@@ -644,65 +643,6 @@ def agg_by_day(x):
644643

645644
tm.assert_frame_equal(result, expected)
646645

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

0 commit comments

Comments
 (0)