Skip to content

BUG: groupby with sort=False creates buggy MultiIndex #32291

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

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ MultiIndex
# Common elements are now guaranteed to be ordered by the left side
left.intersection(right, sort=False)

- Bug in :meth:`MultiIndex.is_lexsorted` was returning incorrect results when the levels of the multiindex weren't monotonic (:issue:`32259`)
-

I/O
Expand Down
11 changes: 8 additions & 3 deletions pandas/core/groupby/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,14 @@ def reconstructed_codes(self) -> List[np.ndarray]:
def result_index(self) -> Index:
if not self.compressed and len(self.groupings) == 1:
return self.groupings[0].result_index.rename(self.names[0])

codes = self.reconstructed_codes
levels = [ping.result_index for ping in self.groupings]
codes = []
levels = []
for code, ping in zip(self.reconstructed_codes, self.groupings):
levels.append(ping.result_index)
if ping.result_index.is_monotonic:
codes.append(code)
else:
codes.append(algorithms.factorize(ping.grouper, sort=True)[0])
result = MultiIndex(
levels=levels, codes=codes, verify_integrity=False, names=self.names
)
Expand Down
24 changes: 24 additions & 0 deletions pandas/tests/groupby/test_groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -2015,6 +2015,30 @@ def test_dup_labels_output_shape(groupby_func, idx):
tm.assert_index_equal(result.columns, idx)


def test_sort_false_multiindex_lexsorted():
# GH 32259
d = pd.to_datetime(
[
"2020-11-02",
"2019-01-02",
"2020-01-02",
"2020-02-04",
"2020-11-03",
"2019-11-03",
"2019-11-13",
"2019-11-13",
]
)
a = np.arange(len(d))
b = np.random.rand(len(d))
df = pd.DataFrame({"d": d, "a": a, "b": b})
t = df.groupby(["d", "a"], sort=False).mean()
assert not t.index.is_lexsorted()

t = df.groupby(["d", "a"], sort=True).mean()
assert t.index.is_lexsorted()


def test_groupby_crash_on_nunique(axis):
# Fix following 30253
df = pd.DataFrame({("A", "B"): [1, 2], ("A", "C"): [1, 3], ("D", "B"): [0, 0]})
Expand Down