Skip to content

BUG: MultiIndex.append not checking names for equality #48288

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 30, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.6.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ Missing

MultiIndex
^^^^^^^^^^
-
- Bug in :meth:´MultiIndex.append` not checking names for equality (:issue:`48288`)
-

I/O
Expand Down
12 changes: 5 additions & 7 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -2203,21 +2203,19 @@ def append(self, other):
if all(
(isinstance(o, MultiIndex) and o.nlevels >= self.nlevels) for o in other
):
arrays = []
arrays, names = [], []
for i in range(self.nlevels):
label = self._get_level_values(i)
appended = [o._get_level_values(i) for o in other]
arrays.append(label.append(appended))
return MultiIndex.from_arrays(arrays, names=self.names)
level_names = {label.name}.union({x.name for x in appended})
names.append(None if len(level_names) > 1 else label.name)
return MultiIndex.from_arrays(arrays, names=names)

to_concat = (self._values,) + tuple(k._values for k in other)
new_tuples = np.concatenate(to_concat)

# if all(isinstance(x, MultiIndex) for x in other):
try:
return MultiIndex.from_tuples(new_tuples, names=self.names)
except (TypeError, IndexError):
return Index._with_infer(new_tuples)
return Index._with_infer(new_tuples)

def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]:
return self._values.argsort(*args, **kwargs)
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/indexes/multi/test_reshape.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,16 @@ def test_append_index():
tm.assert_index_equal(result, expected)


@pytest.mark.parametrize("name, exp", [("b", "b"), ("c", None)])
def test_append_names_match(name, exp):
# GH#48288
midx = MultiIndex.from_arrays([[1, 2], [3, 4]], names=["a", "b"])
midx2 = MultiIndex.from_arrays([[3], [5]], names=["a", name])
result = midx.append(midx2)
expected = MultiIndex.from_arrays([[1, 2, 3], [3, 4, 5]], names=["a", exp])
tm.assert_index_equal(result, expected)


def test_repeat():
reps = 2
numbers = [1, 2, 3]
Expand Down