Skip to content

Commit ee6e91c

Browse files
Backport PR #36141: BUG: copying series into empty dataframe does not preserve dataframe index name (#36221)
Co-authored-by: Irv Lustig <[email protected]>
1 parent 2afdb3d commit ee6e91c

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

doc/source/whatsnew/v1.1.2.rst

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Bug fixes
4343
- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`)
4444
- Bug in :meth:`DataFrame.corr` causing subsequent indexing lookups to be incorrect (:issue:`35882`)
4545
- Bug in :meth:`import_optional_dependency` returning incorrect package names in cases where package name is different from import name (:issue:`35948`)
46+
- Bug when setting empty :class:`DataFrame` column to a :class:`Series` in preserving name of index in frame (:issue:`31368`)
4647

4748
.. ---------------------------------------------------------------------------
4849

pandas/core/frame.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -3170,9 +3170,11 @@ def _ensure_valid_index(self, value):
31703170
"and a value that cannot be converted to a Series"
31713171
) from err
31723172

3173-
self._mgr = self._mgr.reindex_axis(
3174-
value.index.copy(), axis=1, fill_value=np.nan
3175-
)
3173+
# GH31368 preserve name of index
3174+
index_copy = value.index.copy()
3175+
index_copy.name = self.index.name
3176+
3177+
self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)
31763178

31773179
def _box_col_values(self, values, loc: int) -> Series:
31783180
"""

pandas/tests/indexing/test_partial.py

+12
Original file line numberDiff line numberDiff line change
@@ -660,3 +660,15 @@ def test_indexing_timeseries_regression(self):
660660
expected = Series(rng, index=rng)
661661

662662
tm.assert_series_equal(result, expected)
663+
664+
def test_index_name_empty(self):
665+
# GH 31368
666+
df = pd.DataFrame({}, index=pd.RangeIndex(0, name="df_index"))
667+
series = pd.Series(1.23, index=pd.RangeIndex(4, name="series_index"))
668+
669+
df["series"] = series
670+
expected = pd.DataFrame(
671+
{"series": [1.23] * 4}, index=pd.RangeIndex(4, name="df_index")
672+
)
673+
674+
tm.assert_frame_equal(df, expected)

0 commit comments

Comments
 (0)