Skip to content

Commit

Permalink
Backport PR #36141: BUG: copying series into empty dataframe does not…
Browse files Browse the repository at this point in the history
… preserve dataframe index name (#36221)

Co-authored-by: Irv Lustig <irv@princeton.com>
  • Loading branch information
meeseeksmachine and Dr-Irv authored Sep 8, 2020
1 parent 2afdb3d commit ee6e91c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Bug fixes
- 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`)
- Bug in :meth:`DataFrame.corr` causing subsequent indexing lookups to be incorrect (:issue:`35882`)
- Bug in :meth:`import_optional_dependency` returning incorrect package names in cases where package name is different from import name (:issue:`35948`)
- Bug when setting empty :class:`DataFrame` column to a :class:`Series` in preserving name of index in frame (:issue:`31368`)

.. ---------------------------------------------------------------------------
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3170,9 +3170,11 @@ def _ensure_valid_index(self, value):
"and a value that cannot be converted to a Series"
) from err

self._mgr = self._mgr.reindex_axis(
value.index.copy(), axis=1, fill_value=np.nan
)
# GH31368 preserve name of index
index_copy = value.index.copy()
index_copy.name = self.index.name

self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan)

def _box_col_values(self, values, loc: int) -> Series:
"""
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/indexing/test_partial.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,3 +660,15 @@ def test_indexing_timeseries_regression(self):
expected = Series(rng, index=rng)

tm.assert_series_equal(result, expected)

def test_index_name_empty(self):
# GH 31368
df = pd.DataFrame({}, index=pd.RangeIndex(0, name="df_index"))
series = pd.Series(1.23, index=pd.RangeIndex(4, name="series_index"))

df["series"] = series
expected = pd.DataFrame(
{"series": [1.23] * 4}, index=pd.RangeIndex(4, name="df_index")
)

tm.assert_frame_equal(df, expected)

0 comments on commit ee6e91c

Please sign in to comment.