Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
is_list_like,
is_scalar,
is_sequence,
is_string_dtype,
needs_i8_conversion,
pandas_dtype,
)
Expand Down Expand Up @@ -4454,8 +4455,12 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:
cols_droplevel = maybe_droplevels(cols, key)
if (
not isinstance(cols_droplevel, MultiIndex)
and is_string_dtype(cols_droplevel.dtype)
and not cols_droplevel.any()
):
# if cols_droplevel contains only empty strings,
# value.reindex(cols_droplevel, axis=1) would be full of NaNs
# see GH#62518 and GH#61841
return
if len(cols_droplevel) and not cols_droplevel.equals(value.columns):
value = value.reindex(cols_droplevel, axis=1)
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/indexing/multiindex/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,12 @@ def test_multiindex_assign_aligns_as_implicit_tuple(self):
df1["C"] = s1
tm.assert_frame_equal(df1, df2)
tm.assert_frame_equal(df1, df3)

# GH 62518
df4 = DataFrame(
columns=MultiIndex.from_arrays(
[["a", "a", "z", "z"], pd.Categorical([1, 2, 1, 2])],
),
dtype=object,
)
df4["z"] = df4["z"].astype("int64")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you make this a separate test that uses the exact code snippet in the original issue?

Loading