Skip to content

ENH: Add na_position support to midx.sort_values #51651

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 3 commits into from
Mar 8, 2023
Merged
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/v2.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ enhancement2

Other enhancements
^^^^^^^^^^^^^^^^^^
- :meth:`MultiIndex.sort_values` now supports ``na_position`` (:issue:`51612`)
- :meth:`MultiIndex.sortlevel` and :meth:`Index.sortlevel` gained a new keyword ``na_position`` (:issue:`51612`)
- Improve error message when setting :class:`DataFrame` with wrong number of columns through :meth:`DataFrame.isetitem` (:issue:`51701`)
- Let :meth:`DataFrame.to_feather` accept a non-default :class:`Index` and non-string column names (:issue:`51787`)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5597,7 +5597,7 @@ def sort_values(
items=idx, ascending=ascending, na_position=na_position, key=key
)
else:
_as = idx.argsort()
_as = idx.argsort(na_position=na_position)
if not ascending:
_as = _as[::-1]

Expand Down
8 changes: 6 additions & 2 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2132,11 +2132,15 @@ def append(self, other):
except (TypeError, IndexError):
return Index(new_tuples)

def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
def argsort(
self, *args, na_position: str = "last", **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_incomparable=True)
return lexsort_indexer(target._get_codes_for_sorting())
return lexsort_indexer(
target._get_codes_for_sorting(), na_position=na_position
)
return self._values.argsort(*args, **kwargs)

@Appender(_index_shared_docs["repeat"] % _index_doc_kwargs)
Expand Down
25 changes: 25 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,
Series,
Timestamp,
)
import pandas._testing as tm
Expand Down Expand Up @@ -311,3 +312,27 @@ def test_sort_values_incomparable():
match = "'<' not supported between instances of 'Timestamp' and 'int'"
with pytest.raises(TypeError, match=match):
mi.sort_values()


@pytest.mark.parametrize("na_position", ["first", "last"])
@pytest.mark.parametrize("dtype", ["float64", "Int64", "Float64"])
def test_sort_values_with_na_na_position(dtype, na_position):
# 51612
arrays = [
Series([1, 1, 2], dtype=dtype),
Series([1, None, 3], dtype=dtype),
]
index = MultiIndex.from_arrays(arrays)
result = index.sort_values(na_position=na_position)
if na_position == "first":
arrays = [
Series([1, 1, 2], dtype=dtype),
Series([None, 1, 3], dtype=dtype),
]
else:
arrays = [
Series([1, 1, 2], dtype=dtype),
Series([1, None, 3], dtype=dtype),
]
expected = MultiIndex.from_arrays(arrays)
tm.assert_index_equal(result, expected)