Skip to content

BUG: RollingGroupby not respecting sort=False #36911

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Oct 9, 2020
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.1.4.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ including other versions of pandas.

Fixed regressions
~~~~~~~~~~~~~~~~~
-
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)

.. ---------------------------------------------------------------------------

Expand Down
12 changes: 10 additions & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -563,8 +563,16 @@ def indices(self):
if isinstance(self.grouper, ops.BaseGrouper):
return self.grouper.indices

values = Categorical(self.grouper)
return values._reverse_indexer()
if self.sort:
values = Categorical(self.grouper)
return values._reverse_indexer()
else:
# GH 36889
indices_dict = {}
codes, uniques = algorithms.factorize(self.grouper, sort=False)
for i, category in enumerate(uniques):
indices_dict[category] = np.flatnonzero(codes == i)
return indices_dict

@property
def codes(self) -> np.ndarray:
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/window/test_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,3 +428,18 @@ def test_groupby_rolling_empty_frame(self):
result = expected.groupby(["s1", "s2"]).rolling(window=1).sum()
expected.index = pd.MultiIndex.from_tuples([], names=["s1", "s2", None])
tm.assert_frame_equal(result, expected)

def test_groupby_rolling_no_sort(self):
# GH 36889
result = (
pd.DataFrame({"foo": [2, 1], "bar": [2, 1]})
.groupby("foo", sort=False)
.rolling(1)
.min()
)
expected = pd.DataFrame(
np.array([[2.0, 2.0], [1.0, 1.0]]),
columns=["foo", "bar"],
index=pd.MultiIndex.from_tuples([(2, 0), (1, 1)], names=["foo", None]),
)
tm.assert_frame_equal(result, expected)