Skip to content

Commit

Permalink
Backport PR #53060 on branch 2.0.x (REGR: df.loc setitem losing midx …
Browse files Browse the repository at this point in the history
…names) (#53080)

Backport PR #53060: REGR: df.loc setitem losing midx names

Co-authored-by: Patrick Hoefler <61934744+phofl@users.noreply.github.com>
  • Loading branch information
meeseeksmachine and phofl committed May 4, 2023
1 parent 1bb9365 commit 71601f5
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ including other versions of pandas.

Fixed regressions
~~~~~~~~~~~~~~~~~
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
-

.. ---------------------------------------------------------------------------
Expand Down
7 changes: 6 additions & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9538,7 +9538,12 @@ def _append(
"or if the Series has a name"
)

index = Index([other.name], name=self.index.name)
index = Index(
[other.name],
name=self.index.names
if isinstance(self.index, MultiIndex)
else self.index.name,
)
row_df = other.to_frame().T
# infer_objects is needed for
# test_append_empty_frame_to_series_with_dateutil_tz
Expand Down
15 changes: 15 additions & 0 deletions pandas/tests/indexing/multiindex/test_setitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,21 @@ def test_setitem_new_column_all_na(self):
df["new"] = s
assert df["new"].isna().all()

def test_setitem_enlargement_keep_index_names(self):
# GH#53053
mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
mi_expected = MultiIndex.from_tuples(
[(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
)
expected = DataFrame(
data=[[10, 20, 30], [10, 20, 30]],
index=mi_expected,
columns=["A", "B", "C"],
)
tm.assert_frame_equal(df, expected)


@td.skip_array_manager_invalid_test # df["foo"] select multiple columns -> .values
# is not a view
Expand Down

0 comments on commit 71601f5

Please sign in to comment.