Skip to content
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
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
21 changes: 21 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,24 @@ def test_multiindex_assign_aligns_as_implicit_tuple(self):
df1["C"] = s1
tm.assert_frame_equal(df1, df2)
tm.assert_frame_equal(df1, df3)

def test_multiindex_assign_alignment_with_non_string_dtype(self):
# GH 62518
columns = MultiIndex.from_arrays(
[["a", "a", "z", "z"], pd.Categorical([1, 2, 1, 2])]
)

meta = DataFrame(columns=columns, dtype=object)
meta["z"] = meta["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.

Sorry, one more thing. Could you use tm.assert_frame.equal to assert that meta is equal to a new DataFrame that's the result of this casting?


result = DataFrame(
data={
("a", 1): Series([], dtype=object),
("a", 2): Series([], dtype=object),
("z", 1): Series([], dtype="int64"),
("z", 2): Series([], dtype="int64"),
},
columns=columns,
)

tm.assert_frame_equal(meta, result)
Loading