Skip to content

Commit 54777c7

Browse files
authored
Regression in loc.setitem losing mi names when df is empty (#46322)
1 parent e252dd7 commit 54777c7

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
@@ -18,6 +18,7 @@ Fixed regressions
1818
- Fixed regression in :func:`read_csv` killing python process when invalid file input was given for ``engine="c"`` (:issue:`45957`)
1919
- Fixed memory performance regression in :meth:`Series.fillna` when called on a :class:`DataFrame` column with ``inplace=True`` (:issue:`46149`)
2020
- 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`)
21+
- Fixed regression in :meth:`DataFrame.loc.__setitem__` losing :class:`MultiIndex` names if :class:`DataFrame` was empty before (:issue:`46317`)
2122
-
2223

2324
.. ---------------------------------------------------------------------------

pandas/core/indexing.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -2094,7 +2094,14 @@ def _setitem_with_indexer_missing(self, indexer, value):
20942094
# We will ignore the existing dtypes instead of using
20952095
# internals.concat logic
20962096
df = value.to_frame().T
2097-
df.index = Index([indexer], name=self.obj.index.name)
2097+
2098+
idx = self.obj.index
2099+
if isinstance(idx, MultiIndex):
2100+
name = idx.names
2101+
else:
2102+
name = idx.name
2103+
2104+
df.index = Index([indexer], name=name)
20982105
if not has_dtype:
20992106
# i.e. if we already had a Series or ndarray, keep that
21002107
# 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
@@ -1281,6 +1281,18 @@ def test_loc_expand_empty_frame_keep_index_name(self):
12811281
expected = DataFrame({"b": [1]}, index=Index([0], name="a"))
12821282
tm.assert_frame_equal(df, expected)
12831283

1284+
def test_loc_expand_empty_frame_keep_midx_names(self):
1285+
# GH#46317
1286+
df = DataFrame(
1287+
columns=["d"], index=MultiIndex.from_tuples([], names=["a", "b", "c"])
1288+
)
1289+
df.loc[(1, 2, 3)] = "foo"
1290+
expected = DataFrame(
1291+
{"d": ["foo"]},
1292+
index=MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]),
1293+
)
1294+
tm.assert_frame_equal(df, expected)
1295+
12841296

12851297
class TestDataFrameIndexingUInt64:
12861298
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)