From 4b2e1f983ed39f015b12665e9f599a2cd6ade436 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Fri, 5 May 2023 21:26:23 +0200 Subject: [PATCH] Backport PR #53102: REGR: MultiIndex.join not resorting levels of new index --- doc/source/whatsnew/v2.0.2.rst | 2 ++ pandas/core/indexes/base.py | 2 +- pandas/tests/indexes/multi/test_join.py | 12 ++++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst index ae251f25de578..7864791f8bc59 100644 --- a/doc/source/whatsnew/v2.0.2.rst +++ b/doc/source/whatsnew/v2.0.2.rst @@ -15,6 +15,8 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`) - Fixed regression in :meth:`DataFrame.to_string` printing a backslash at the end of the first row of data, instead of headers, when the DataFrame doesn't fit the line width (:issue:`53054`) +- Fixed regression in :meth:`MultiIndex.join` returning levels in wrong order (:issue:`53093`) +- .. --------------------------------------------------------------------------- .. _whatsnew_202.bug_fixes: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 890ac084680a1..e2b8400188136 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4877,7 +4877,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)