Skip to content

Commit e211883

Browse files
authored
Fix MultiIndex.union with duplicates and differing names (#62738)
1 parent 1af720a commit e211883

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,6 +1056,7 @@ MultiIndex
10561056
- :func:`MultiIndex.get_level_values` accessing a :class:`DatetimeIndex` does not carry the frequency attribute along (:issue:`58327`, :issue:`57949`)
10571057
- Bug in :class:`DataFrame` arithmetic operations in case of unaligned MultiIndex columns (:issue:`60498`)
10581058
- Bug in :class:`DataFrame` arithmetic operations with :class:`Series` in case of unaligned MultiIndex (:issue:`61009`)
1059+
- Bug in :meth:`MultiIndex.union` raising when indexes have duplicates with differing names (:issue:`62059`)
10591060
- Bug in :meth:`MultiIndex.from_tuples` causing wrong output with input of type tuples having NaN values (:issue:`60695`, :issue:`60988`)
10601061
- Bug in :meth:`DataFrame.__setitem__` where column alignment logic would reindex the assigned value with an empty index, incorrectly setting all values to ``NaN``.(:issue:`61841`)
10611062
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` where reindexing :class:`Index` to a :class:`MultiIndex` would incorrectly set all values to ``NaN``.(:issue:`60923`)

pandas/core/indexes/multi.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3946,7 +3946,9 @@ def _union(self, other, sort) -> MultiIndex:
39463946
if other.has_duplicates:
39473947
# This is only necessary if other has dupes,
39483948
# otherwise difference is faster
3949-
result = super()._union(other, sort)
3949+
result = super(MultiIndex, self.rename(result_names))._union(
3950+
other.rename(result_names), sort
3951+
)
39503952

39513953
if isinstance(result, MultiIndex):
39523954
return result

pandas/tests/indexes/multi/test_setops.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,6 +687,18 @@ def test_union_keep_ea_dtype_with_na(any_numeric_ea_dtype):
687687
tm.assert_index_equal(result, expected)
688688

689689

690+
def test_union_duplicates_different_names():
691+
# GH#62059
692+
mi1 = MultiIndex.from_tuples([(1, "a"), (2, "b")], names=["x", "y"])
693+
mi2 = MultiIndex.from_tuples([(2, "b"), (3, "c"), (2, "b")])
694+
695+
result = mi1.union(mi2)
696+
expected = MultiIndex.from_tuples(
697+
[(1, "a"), (2, "b"), (2, "b"), (3, "c")], names=[None, None]
698+
)
699+
tm.assert_index_equal(result, expected)
700+
701+
690702
@pytest.mark.parametrize(
691703
"levels1, levels2, codes1, codes2, names",
692704
[

0 commit comments

Comments
 (0)