Skip to content

Commit b4182fa

Browse files
mlondschienJulianWgs
authored andcommitted
Allow to union MultiIndex with empty RangeIndex (pandas-dev#41275)
1 parent 9416263 commit b4182fa

File tree

4 files changed

+28
-3
lines changed

4 files changed

+28
-3
lines changed

pandas/core/indexes/base.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -2923,8 +2923,10 @@ def union(self, other, sort=None):
29232923
other, result_name = self._convert_can_do_setop(other)
29242924

29252925
if not is_dtype_equal(self.dtype, other.dtype):
2926-
if isinstance(self, ABCMultiIndex) and not is_object_dtype(
2927-
unpack_nested_dtype(other)
2926+
if (
2927+
isinstance(self, ABCMultiIndex)
2928+
and not is_object_dtype(unpack_nested_dtype(other))
2929+
and len(other) > 0
29282930
):
29292931
raise NotImplementedError(
29302932
"Can only union MultiIndex with MultiIndex or Index of tuples, "

pandas/core/indexes/multi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3597,7 +3597,7 @@ def _get_reconciled_name_object(self, other) -> MultiIndex:
35973597
def _maybe_match_names(self, other):
35983598
"""
35993599
Try to find common names to attach to the result of an operation between
3600-
a and b. Return a consensus list of names if they match at least partly
3600+
a and b. Return a consensus list of names if they match at least partly
36013601
or list of None if they have completely different names.
36023602
"""
36033603
if len(self.names) != len(other.names):

pandas/tests/indexes/multi/test_setops.py

+12
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,18 @@ def test_union_empty_self_different_names():
414414
tm.assert_index_equal(result, expected)
415415

416416

417+
def test_union_multiindex_empty_rangeindex():
418+
# GH#41234
419+
mi = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
420+
ri = pd.RangeIndex(0)
421+
422+
result_left = mi.union(ri)
423+
tm.assert_index_equal(mi, result_left, check_names=False)
424+
425+
result_right = ri.union(mi)
426+
tm.assert_index_equal(mi, result_right, check_names=False)
427+
428+
417429
@pytest.mark.parametrize(
418430
"method", ["union", "intersection", "difference", "symmetric_difference"]
419431
)

pandas/tests/reshape/concat/test_concat.py

+11
Original file line numberDiff line numberDiff line change
@@ -627,3 +627,14 @@ def test_concat_null_object_with_dti():
627627
index=exp_index,
628628
)
629629
tm.assert_frame_equal(result, expected)
630+
631+
632+
def test_concat_multiindex_with_empty_rangeindex():
633+
# GH#41234
634+
mi = MultiIndex.from_tuples([("B", 1), ("C", 1)])
635+
df1 = DataFrame([[1, 2]], columns=mi)
636+
df2 = DataFrame(index=[1], columns=pd.RangeIndex(0))
637+
638+
result = concat([df1, df2])
639+
expected = DataFrame([[1, 2], [np.nan, np.nan]], columns=mi)
640+
tm.assert_frame_equal(result, expected)

0 commit comments

Comments
 (0)