From d8ff24e7ef4938f00d67b48fb913bf78a7424d3b Mon Sep 17 00:00:00 2001 From: Luke Manley Date: Sat, 18 Nov 2023 12:20:07 -0500 Subject: [PATCH 1/2] fix sort_index regression --- pandas/core/sorting.py | 4 ++-- pandas/tests/series/methods/test_sort_index.py | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 1b1d9d7640058..a431842218b3b 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -98,8 +98,8 @@ def get_indexer_indexer( sort_remaining=sort_remaining, na_position=na_position, ) - elif (ascending and target.is_monotonic_increasing) or ( - not ascending and target.is_monotonic_decreasing + elif (np.all(ascending) and target.is_monotonic_increasing) or ( + not np.any(ascending) and target.is_monotonic_decreasing ): # Check monotonic-ness before sort an index (GH 11080) return None diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index c5d4694f8bdbd..f91e63fe3d131 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -317,3 +317,21 @@ def test_sort_values_key_type(self): result = s.sort_index(key=lambda x: x.month_name()) expected = s.iloc[[2, 1, 0]] tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "ascending", + [ + [True, False], + [False, True], + ], + ) + def test_sort_index_multi_already_monotonic(self, ascending): + # GH ##### + mi = MultiIndex.from_product([[1, 2], [3, 4]]) + ser = Series(range(len(mi)), index=mi) + result = ser.sort_index(ascending=ascending) + if ascending == [True, False]: + expected = ser.take([1, 0, 3, 2]) + elif ascending == [False, True]: + expected = ser.take([2, 3, 0, 1]) + tm.assert_series_equal(result, expected) From 0ae49b72d031dda68cfae75c83d00b221d698e5e Mon Sep 17 00:00:00 2001 From: Luke Manley Date: Sat, 18 Nov 2023 12:26:14 -0500 Subject: [PATCH 2/2] gh ref --- pandas/tests/series/methods/test_sort_index.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index f91e63fe3d131..d6817aa179b7b 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -326,7 +326,7 @@ def test_sort_values_key_type(self): ], ) def test_sort_index_multi_already_monotonic(self, ascending): - # GH ##### + # GH 56049 mi = MultiIndex.from_product([[1, 2], [3, 4]]) ser = Series(range(len(mi)), index=mi) result = ser.sort_index(ascending=ascending)