Skip to content

REGR: sort_value can not sort levels with non nas and nans #48626

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 1 commit 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
9 changes: 6 additions & 3 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2226,9 +2226,12 @@ 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)
if not any(-1 in code for code in self.codes):
# 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)
return self._values.argsort(*args, **kwargs)

@Appender(_index_shared_docs["repeat"] % _index_doc_kwargs)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/indexes/multi/test_sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,3 +280,13 @@ def test_remove_unused_levels_with_nan():
result = idx.levels
expected = FrozenList([["a", np.nan], [4]])
assert str(result) == str(expected)


def test_sort_values_nan():
# GH#
midx = MultiIndex(levels=[["A", "B", "C"], ["D"]], codes=[[1, 0, 2], [-1, -1, 0]])
result = midx.sort_values()
expected = MultiIndex(
levels=[["A", "B", "C"], ["D"]], codes=[[0, 1, 2], [-1, -1, 0]]
)
tm.assert_index_equal(result, expected)