Skip to content

BUG: Bug Multiindex assignment with an aligned rhs (but at different levels) (GH7475) #7476

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

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 1 addition & 2 deletions doc/source/v0.14.1.txt
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,7 @@ Bug Fixes
~~~~~~~~~




- Bug Multiindex assignment with an aligned rhs (but at different levels) (:issue:`7475`)



Expand Down
13 changes: 13 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -1980,6 +1980,19 @@ def _set_item(self, key, value):

is_existing = key in self.columns
self._ensure_valid_index(value)

# have a new column, a multi-index, but no specification for the index,
# have to assume first level; this in effect broadcasts across the index
# GH 7475
if not is_existing and isinstance(self.columns, MultiIndex) and not isinstance(key, tuple):
value_columns = self.columns.set_levels([[key]] + self.columns.levels[1:])
value = self._sanitize_column(key, value)
if len(value_columns) != value.ndim:
raise ValueError("cannot assign to a multi-index with invalid dimensions")
for i, v in zip(value_columns,value):
NDFrame._set_item(self, i, v)
return self

value = self._sanitize_column(key, value)
NDFrame._set_item(self, key, value)

Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1828,6 +1828,18 @@ def f():
df.loc['bar'] *= 2
self.assertRaises(TypeError, f)

def test_multiindex_setitem(self):

# GH 7475
# multi-index assignment

df_orig = DataFrame(np.arange(10,dtype='int64').reshape(-1,2), columns=pd.MultiIndex.from_tuples([('Val','A'),('Val','B')]))
expected = concat([df_orig['Val'],df_orig['Val']/2],axis=1,keys=['Val','Half'])

df = df_orig.copy()
df['Half'] = df['Val']/2
assert_frame_equal(df,expected)

def test_getitem_multiindex(self):

# GH 5725
Expand Down