Skip to content

Commit 6766d0b

Browse files
committed
fix(frame): ensure proper name attribute when setting new column with scalar value
- Address issue where name attribute was lost when setting new column with scalar value and tuple key in MultiIndex DataFrame - Implement check for tuple key and scalar value in MultiIndex DataFrame - Create Series with proper name to ensure name attribute matches the key - Update test case to assert Series name in scalar assignment with MultiIndex
1 parent 3b36a2f commit 6766d0b

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

pandas/core/frame.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4517,7 +4517,20 @@ def _set_item(self, key, value) -> None:
45174517
Series/TimeSeries will be conformed to the DataFrames index to
45184518
ensure homogeneity.
45194519
"""
4520-
value, refs = self._sanitize_column(value)
4520+
# Check if we're setting a new column with a tuple key in a MultiIndex DataFrame
4521+
# and the value is a scalar. In this case, we need to create a Series with the
4522+
# proper name to ensure the name attribute matches the key.
4523+
if (
4524+
isinstance(key, tuple)
4525+
and isinstance(self.columns, MultiIndex)
4526+
and not is_list_like(value)
4527+
and key not in self.columns
4528+
):
4529+
# Create a Series with the proper name
4530+
value = Series([value] * len(self.index), index=self.index, name=key)
4531+
value, refs = self._sanitize_column(value)
4532+
else:
4533+
value, refs = self._sanitize_column(value)
45214534

45224535
if (
45234536
key in self.columns

pandas/tests/frame/indexing/test_setitem.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -653,10 +653,12 @@ def test_setitem_multiindex_scalar_indexer(self):
653653
# Test scalar assignment with 3-level MultiIndex
654654
df_3level[("Z", "C", "3")] = 42
655655
assert ("Z", "C", "3") in df_3level.columns
656-
tm.assert_series_equal(df_3level[("Z", "C", "3")], Series([42, 42, 42, 42]))
656+
tm.assert_series_equal(
657+
df_3level[("Z", "C", "3")], Series([42, 42, 42, 42], name=("Z", "C", "3"))
658+
)
657659

658660
# Test Series assignment with 3-level MultiIndex
659-
new_series = Series([1, 2, 3, 4])
661+
new_series = Series([1, 2, 3, 4], name=("W", "D", "4"))
660662
df_3level[("W", "D", "4")] = new_series
661663
tm.assert_series_equal(df_3level[("W", "D", "4")], new_series)
662664

0 commit comments

Comments
 (0)