From 1e9bce2f9e1d0465e139d2f1b55d82ca5624db90 Mon Sep 17 00:00:00 2001 From: Patrick Hoefler <61934744+phofl@users.noreply.github.com> Date: Thu, 27 Jan 2022 00:35:01 +0100 Subject: [PATCH] Backport PR #45623: REGR: loc.setitem losing index name when df was empty before --- doc/source/whatsnew/v1.4.1.rst | 1 + pandas/core/indexing.py | 2 +- pandas/tests/frame/indexing/test_indexing.py | 7 +++++++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 79dae514b77e9..026051d126d5b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 77482cbc88bf5..91255c563b2d3 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2003,7 +2003,7 @@ def _setitem_with_indexer_missing(self, indexer, value): # We will ignore the existing dtypes instead of using # internals.concat logic df = value.to_frame().T - df.index = [indexer] + df.index = Index([indexer], name=self.obj.index.name) if not has_dtype: # i.e. if we already had a Series or ndarray, keep that # dtype. But if we had a list or dict, then do inference diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 8f9caf1cd13aa..23927b3d3264e 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1281,6 +1281,13 @@ def test_setting_mismatched_na_into_nullable_fails( with pytest.raises(TypeError, match=msg): df2.iloc[:2, 0] = [null, null] + def test_loc_expand_empty_frame_keep_index_name(self): + # GH#45621 + df = DataFrame(columns=["b"], index=Index([], name="a")) + df.loc[0] = 1 + expected = DataFrame({"b": [1]}, index=Index([0], name="a")) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame):