Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BUG: copying series into empty dataframe does not preserve dataframe index name #36141

Merged
merged 5 commits into from
Sep 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -42,6 +42,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 @@ -3206,9 +3206,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()
jreback marked this conversation as resolved.
Show resolved Hide resolved
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)