Skip to content

Backport PR #27855 on branch 0.25.x (BUG: add back check for MultiIndex case and take_split_path) #27887

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

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
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.1.rst
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ Indexing

- Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`)
- Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`)
-
- Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`).
-

Missing
Expand Down
11 changes: 11 additions & 0 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,17 @@ def _setitem_with_indexer(self, indexer, value):
val = list(value.values()) if isinstance(value, dict) else value
take_split_path = not blk._can_hold_element(val)

# if we have any multi-indexes that have non-trivial slices
# (not null slices) then we must take the split path, xref
# GH 10360, GH 27841
if isinstance(indexer, tuple) and len(indexer) == len(self.obj.axes):
for i, ax in zip(indexer, self.obj.axes):
if isinstance(ax, MultiIndex) and not (
is_integer(i) or com.is_null_slice(i)
):
take_split_path = True
break

if isinstance(indexer, tuple):
nindexer = []
for i, idx in enumerate(indexer):
Expand Down
23 changes: 23 additions & 0 deletions pandas/tests/indexing/multiindex/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,26 @@ def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data):
expected = 0
result = df.sort_index().loc[("bar", "three"), "B"]
assert result == expected


def test_loc_setitem_single_column_slice():
# case from https://github.com/pandas-dev/pandas/issues/27841
df = DataFrame(
"string",
index=list("abcd"),
columns=MultiIndex.from_product([["Main"], ("another", "one")]),
)
df["labels"] = "a"
df.loc[:, "labels"] = df.index
tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index))

# test with non-object block
df = DataFrame(
np.nan,
index=range(4),
columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]),
)
expected = df.copy()
df.loc[:, "B"] = np.arange(4)
expected.iloc[:, 2] = np.arange(4)
tm.assert_frame_equal(df, expected)