Skip to content

Commit 1cae4e4

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#46322: Regression in loc.setitem losing mi names when df is empty
1 parent 92d7992 commit 1cae4e4

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v1.4.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Fixed regressions
1717
- Fixed regression in :meth:`DataFrame.drop` and :meth:`Series.drop` when :class:`Index` had extension dtype and duplicates (:issue:`45860`)
1818
- Fixed memory performance regression in :meth:`Series.fillna` when called on a :class:`DataFrame` column with ``inplace=True`` (:issue:`46149`)
1919
- Provided an alternative solution for passing custom Excel formats in :meth:`.Styler.to_excel`, which was a regression based on stricter CSS validation. Examples available in the documentation for :meth:`.Styler.format` (:issue:`46152`)
20+
- Fixed regression in :meth:`DataFrame.loc.__setitem__` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
2021
-
2122

2223
.. ---------------------------------------------------------------------------

pandas/core/indexing.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -2003,7 +2003,14 @@ def _setitem_with_indexer_missing(self, indexer, value):
20032003
# We will ignore the existing dtypes instead of using
20042004
# internals.concat logic
20052005
df = value.to_frame().T
2006-
df.index = Index([indexer], name=self.obj.index.name)
2006+
2007+
idx = self.obj.index
2008+
if isinstance(idx, MultiIndex):
2009+
name = idx.names
2010+
else:
2011+
name = idx.name
2012+
2013+
df.index = Index([indexer], name=name)
20072014
if not has_dtype:
20082015
# i.e. if we already had a Series or ndarray, keep that
20092016
# dtype. But if we had a list or dict, then do inference

pandas/tests/frame/indexing/test_indexing.py

+12
Original file line numberDiff line numberDiff line change
@@ -1288,6 +1288,18 @@ def test_loc_expand_empty_frame_keep_index_name(self):
12881288
expected = DataFrame({"b": [1]}, index=Index([0], name="a"))
12891289
tm.assert_frame_equal(df, expected)
12901290

1291+
def test_loc_expand_empty_frame_keep_midx_names(self):
1292+
# GH#46317
1293+
df = DataFrame(
1294+
columns=["d"], index=MultiIndex.from_tuples([], names=["a", "b", "c"])
1295+
)
1296+
df.loc[(1, 2, 3)] = "foo"
1297+
expected = DataFrame(
1298+
{"d": ["foo"]},
1299+
index=MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]),
1300+
)
1301+
tm.assert_frame_equal(df, expected)
1302+
12911303

12921304
class TestDataFrameIndexingUInt64:
12931305
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)