Skip to content

Commit f65b693

Browse files
phoflyehoshuadimarsky
authored andcommitted
REGR: loc.setitem losing index name when df was empty before (pandas-dev#45623)
1 parent 1ac7824 commit f65b693

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
@@ -2017,7 +2017,7 @@ def _setitem_with_indexer_missing(self, indexer, value):
20172017
# We will ignore the existing dtypes instead of using
20182018
# internals.concat logic
20192019
df = value.to_frame().T
2020-
df.index = [indexer]
2020+
df.index = Index([indexer], name=self.obj.index.name)
20212021
if not has_dtype:
20222022
# i.e. if we already had a Series or ndarray, keep that
20232023
# 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
@@ -1279,6 +1279,13 @@ def test_setting_mismatched_na_into_nullable_fails(
12791279
with pytest.raises(TypeError, match=msg):
12801280
df2.iloc[:2, 0] = [null, null]
12811281

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

12831290
class TestDataFrameIndexingUInt64:
12841291
def test_setitem(self, uint64_frame):

0 commit comments

Comments
 (0)