Skip to content

BUG/PERF: use lexsort_indexer in MultiIndex.argsort #48495

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 20 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1940,7 +1940,7 @@ def _lexsort_depth(self) -> int:
return self.sortorder
return _lexsort_depth(self.codes, self.nlevels)

def _sort_levels_monotonic(self, raise_if_unsortable: bool = False) -> MultiIndex:
def _sort_levels_monotonic(self, raise_if_incomparable: bool = False) -> MultiIndex:
"""
This is an *internal* function.

Expand Down Expand Up @@ -1987,7 +1987,7 @@ def _sort_levels_monotonic(self, raise_if_unsortable: bool = False) -> MultiInde
# indexer to reorder the levels
indexer = lev.argsort()
except TypeError:
if raise_if_unsortable:
if raise_if_incomparable:
raise
else:
lev = lev.take(indexer)
Expand Down Expand Up @@ -2235,7 +2235,7 @@ def append(self, other):
def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
if len(args) == 0 and len(kwargs) == 0:
# lexsort is significantly faster than self._values.argsort()
target = self._sort_levels_monotonic(raise_if_unsortable=True)
target = self._sort_levels_monotonic(raise_if_incomparable=True)
return lexsort_indexer(target._get_codes_for_sorting())
return self._values.argsort(*args, **kwargs)

Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/indexes/multi/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
Index,
MultiIndex,
RangeIndex,
Timestamp,
)
import pandas._testing as tm
from pandas.core.indexes.frozen import FrozenList
Expand Down Expand Up @@ -289,3 +290,20 @@ def test_sort_values_nan():
levels=[["A", "B", "C"], ["D"]], codes=[[0, 1, 2], [-1, -1, 0]]
)
tm.assert_index_equal(result, expected)


def test_sort_values_monotonic_incomparable():
mi = MultiIndex.from_arrays(
[
[1, Timestamp("2000-01-01")],
[3, 4],
]
)

match = "'<' not supported between instances of 'Timestamp' and 'int'"
with pytest.raises(TypeError, match=match):
mi._sort_levels_monotonic(raise_if_incomparable=True)

result = mi._sort_levels_monotonic()
expected = mi
tm.assert_index_equal(result, expected)