Skip to content

Commit ea85788

Browse files
mroeschkeMatt Roeschke
authored andcommitted
Backport PR pandas-dev#36911: BUG: RollingGroupby not respecting sort=False
Co-authored-by: Matt Roeschke <[email protected]>
1 parent cf4974d commit ea85788

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

doc/source/whatsnew/v1.1.4.rst

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ including other versions of pandas.
1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
18+
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
1819

1920
.. ---------------------------------------------------------------------------
2021

pandas/core/groupby/grouper.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -556,8 +556,13 @@ def indices(self):
556556
if isinstance(self.grouper, ops.BaseGrouper):
557557
return self.grouper.indices
558558

559-
values = Categorical(self.grouper)
560-
return values._reverse_indexer()
559+
# Return a dictionary of {group label: [indices belonging to the group label]}
560+
# respecting whether sort was specified
561+
codes, uniques = algorithms.factorize(self.grouper, sort=self.sort)
562+
return {
563+
category: np.flatnonzero(codes == i)
564+
for i, category in enumerate(Index(uniques))
565+
}
561566

562567
@property
563568
def codes(self) -> np.ndarray:

pandas/tests/window/test_grouper.py

+15
Original file line numberDiff line numberDiff line change
@@ -417,3 +417,18 @@ def test_groupby_rolling_empty_frame(self):
417417
result = expected.groupby(["s1", "s2"]).rolling(window=1).sum()
418418
expected.index = pd.MultiIndex.from_tuples([], names=["s1", "s2", None])
419419
tm.assert_frame_equal(result, expected)
420+
421+
def test_groupby_rolling_no_sort(self):
422+
# GH 36889
423+
result = (
424+
pd.DataFrame({"foo": [2, 1], "bar": [2, 1]})
425+
.groupby("foo", sort=False)
426+
.rolling(1)
427+
.min()
428+
)
429+
expected = pd.DataFrame(
430+
np.array([[2.0, 2.0], [1.0, 1.0]]),
431+
columns=["foo", "bar"],
432+
index=pd.MultiIndex.from_tuples([(2, 0), (1, 1)], names=["foo", None]),
433+
)
434+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)