Skip to content

Commit 1e9bce2

Browse files
phoflmeeseeksmachine
authored andcommitted
Backport PR pandas-dev#45623: REGR: loc.setitem losing index name when df was empty before
1 parent b241701 commit 1e9bce2

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

doc/source/whatsnew/v1.4.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ including other versions of pandas.
1515
Fixed regressions
1616
~~~~~~~~~~~~~~~~~
1717
- Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`)
18+
- Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`)
1819
-
1920

2021
.. ---------------------------------------------------------------------------

pandas/core/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2003,7 +2003,7 @@ 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 = [indexer]
2006+
df.index = Index([indexer], name=self.obj.index.name)
20072007
if not has_dtype:
20082008
# i.e. if we already had a Series or ndarray, keep that
20092009
# dtype. But if we had a list or dict, then do inference

pandas/tests/frame/indexing/test_indexing.py

+7
Original file line numberDiff line numberDiff line change
@@ -1281,6 +1281,13 @@ def test_setting_mismatched_na_into_nullable_fails(
12811281
with pytest.raises(TypeError, match=msg):
12821282
df2.iloc[:2, 0] = [null, null]
12831283

1284+
def test_loc_expand_empty_frame_keep_index_name(self):
1285+
# GH#45621
1286+
df = DataFrame(columns=["b"], index=Index([], name="a"))
1287+
df.loc[0] = 1
1288+
expected = DataFrame({"b": [1]}, index=Index([0], name="a"))
1289+
tm.assert_frame_equal(df, expected)
1290+
12841291

12851292
class TestDataFrameIndexingUInt64:
12861293
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)