Skip to content

Commit 74b5492

Browse files
Dr-IrvKevin D Smith
authored and
Kevin D Smith
committed
BUG: copying series into empty dataframe does not preserve dataframe index name (pandas-dev#36141)
1 parent b410978 commit 74b5492

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
@@ -3206,9 +3206,11 @@ def _ensure_valid_index(self, value):
32063206
"and a value that cannot be converted to a Series"
32073207
) from err
32083208

3209-
self._mgr = self._mgr.reindex_axis(
3210-
value.index.copy(), axis=1, fill_value=np.nan
3211-
)
3209+
# GH31368 preserve name of index
3210+
index_copy = value.index.copy()
3211+
index_copy.name = self.index.name
3212+
3213+
self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)
32123214

32133215
def _box_col_values(self, values, loc: int) -> Series:
32143216
"""

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)