From 91f7307f421d8d4e45e391898fa98d868664d694 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Fri, 5 May 2023 15:56:41 +0200 Subject: [PATCH] REGR: MultiIndex.join not resorting levels of new index --- doc/source/whatsnew/v2.0.2.rst | 1 + pandas/core/indexes/base.py | 2 +- pandas/tests/indexes/multi/test_join.py | 12 ++++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst index 692315bb88d30..d02e841a72225 100644 --- a/doc/source/whatsnew/v2.0.2.rst +++ b/doc/source/whatsnew/v2.0.2.rst @@ -14,6 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`) +- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 841d8bb0749d0..98e71cff09823 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4907,7 +4907,7 @@ def _wrap_joined_index( mask = lidx == -1 join_idx = self.take(lidx) right = other.take(ridx) - join_index = join_idx.putmask(mask, right) + join_index = join_idx.putmask(mask, right)._sort_levels_monotonic() return join_index.set_names(name) # type: ignore[return-value] else: name = get_op_result_name(self, other) diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py index 4fff862961920..c5a3512113655 100644 --- a/pandas/tests/indexes/multi/test_join.py +++ b/pandas/tests/indexes/multi/test_join.py @@ -257,3 +257,15 @@ def test_join_dtypes_all_nan(any_numeric_ea_dtype): ] ) tm.assert_index_equal(result, expected) + + +def test_join_index_levels(): + # GH#53093 + midx = midx = MultiIndex.from_tuples([("a", "2019-02-01"), ("a", "2019-02-01")]) + midx2 = MultiIndex.from_tuples([("a", "2019-01-31")]) + result = midx.join(midx2, how="outer") + expected = MultiIndex.from_tuples( + [("a", "2019-01-31"), ("a", "2019-02-01"), ("a", "2019-02-01")] + ) + tm.assert_index_equal(result.levels[1], expected.levels[1]) + tm.assert_index_equal(result, expected)