Skip to content

Commit ebd378c

Browse files
phoflim-vinicius
authored and
im-vinicius
committed
REGR: df.loc setitem losing midx names (pandas-dev#53060)
1 parent a69a36a commit ebd378c

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

doc/source/whatsnew/v2.0.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ including other versions of pandas.
1313

1414
Fixed regressions
1515
~~~~~~~~~~~~~~~~~
16+
- Fixed regression in :meth:`DataFrame.loc` losing :class:`MultiIndex` name when enlarging object (:issue:`53053`)
1617
-
1718

1819
.. ---------------------------------------------------------------------------

pandas/core/frame.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -9914,7 +9914,12 @@ def _append(
99149914
"or if the Series has a name"
99159915
)
99169916

9917-
index = Index([other.name], name=self.index.name)
9917+
index = Index(
9918+
[other.name],
9919+
name=self.index.names
9920+
if isinstance(self.index, MultiIndex)
9921+
else self.index.name,
9922+
)
99189923
row_df = other.to_frame().T
99199924
# infer_objects is needed for
99209925
# test_append_empty_frame_to_series_with_dateutil_tz

pandas/tests/indexing/multiindex/test_setitem.py

+15
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,21 @@ def test_setitem_new_column_all_na(self):
479479
df["new"] = s
480480
assert df["new"].isna().all()
481481

482+
def test_setitem_enlargement_keep_index_names(self):
483+
# GH#53053
484+
mi = MultiIndex.from_tuples([(1, 2, 3)], names=["i1", "i2", "i3"])
485+
df = DataFrame(data=[[10, 20, 30]], index=mi, columns=["A", "B", "C"])
486+
df.loc[(0, 0, 0)] = df.loc[(1, 2, 3)]
487+
mi_expected = MultiIndex.from_tuples(
488+
[(1, 2, 3), (0, 0, 0)], names=["i1", "i2", "i3"]
489+
)
490+
expected = DataFrame(
491+
data=[[10, 20, 30], [10, 20, 30]],
492+
index=mi_expected,
493+
columns=["A", "B", "C"],
494+
)
495+
tm.assert_frame_equal(df, expected)
496+
482497

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

0 commit comments

Comments
 (0)