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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -994,6 +994,7 @@ MultiIndex
- Bug in :class:`DataFrame` arithmetic operations in case of unaligned MultiIndex columns (:issue:`60498`)
- Bug in :class:`DataFrame` arithmetic operations with :class:`Series` in case of unaligned MultiIndex (:issue:`61009`)
- Bug in :meth:`MultiIndex.from_tuples` causing wrong output with input of type tuples having NaN values (:issue:`60695`, :issue:`60988`)
- Bug in :meth:`DataFrame.__setitem__` where column alignment logic would reindex the assigned value with an empty index, incorrectly setting all values to ``NaN``.(:issue:`61841`)
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` where reindexing :class:`Index` to a :class:`MultiIndex` would incorrectly set all values to ``NaN``.(:issue:`60923`)

I/O
Expand Down
5 changes: 5 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4450,6 +4450,11 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:
loc, (slice, Series, np.ndarray, Index)
):
cols_droplevel = maybe_droplevels(cols, key)
if (
not isinstance(cols_droplevel, MultiIndex)
and not cols_droplevel.any()
):
return
if len(cols_droplevel) and not cols_droplevel.equals(value.columns):
value = value.reindex(cols_droplevel, axis=1)

Expand Down
22 changes: 22 additions & 0 deletions pandas/tests/indexing/multiindex/test_multiindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,25 @@ def test_groupyby_rename_categories_operation_with_multiindex(self, operation):
expected = getattr(a, operation)(b.sort_index(ascending=False))

tm.assert_series_equal(result, expected)

def test_multiindex_assign_aligns_as_implicit_tuple(self):
# GH 61841
cols = MultiIndex.from_tuples([("A", "B")])
df1 = DataFrame([[i] for i in range(3)], columns=cols)
df2 = df1.copy()
df3 = df1.copy()
s1 = df1["A"].rolling(2).mean()
s2 = s1.copy()
s3 = s1.copy()

df2["C"] = s2
df3[("C", "")] = s3
tm.assert_frame_equal(df2, df3)

df1["C"] = s1
tm.assert_frame_equal(df1, df2)
tm.assert_frame_equal(df1, df3)

df1["C"] = s1
tm.assert_frame_equal(df1, df2)
tm.assert_frame_equal(df1, df3)
Loading