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 3 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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ Missing

MultiIndex
^^^^^^^^^^
- Bug in :meth:`MultiIndex.argsort` raising ``TypeError`` when index contains :attr:`NA` (:issue:`48495`)
- Bug in :meth:`MultiIndex.unique` losing extension array dtype (:issue:`48335`)
- Bug in :meth:`MultiIndex.append` not checking names for equality (:issue:`48288`)
-
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2226,9 +2226,9 @@ def append(self, other):

def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
if len(args) == 0 and len(kwargs) == 0:
# np.lexsort is significantly faster than self._values.argsort()
values = [self._get_level_values(i) for i in reversed(range(self.nlevels))]
return np.lexsort(values)
# lexsort is significantly faster than self._values.argsort()
target = self._sort_levels_monotonic()
return lexsort_indexer(target._get_codes_for_sorting())
return self._values.argsort(*args, **kwargs)

@Appender(_index_shared_docs["repeat"] % _index_doc_kwargs)
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/indexing/multiindex/test_sorted.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import pytest

from pandas import (
NA,
DataFrame,
MultiIndex,
Series,
array,
)
import pandas._testing as tm

Expand Down Expand Up @@ -86,6 +88,25 @@ def test_sort_values_key(self):

tm.assert_frame_equal(result, expected)

def test_sort_values_with_na(self):
arrays = [
array([2, 1, NA], dtype="Int64"),
array([1, 2, 3], dtype="Int64"),
]
index = MultiIndex.from_arrays(arrays)
index = index.sort_values()
result = DataFrame(range(3), index=index)

arrays = [
array([1, 2, NA], dtype="Int64"),
array([2, 1, 3], dtype="Int64"),
]
index = MultiIndex.from_arrays(arrays)
index = index.sort_values()
expected = DataFrame(range(3), index=index)

tm.assert_frame_equal(result, expected)

def test_frame_getitem_not_sorted(self, multiindex_dataframe_random_data):
frame = multiindex_dataframe_random_data
df = frame.T
Expand Down