Skip to content

BUG: loc raising error for MultiIndex with bool indexer #49766

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
merged 1 commit into from
Nov 18, 2022
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/v2.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,7 @@ Indexing
^^^^^^^^
- Bug in :meth:`DataFrame.reindex` filling with wrong values when indexing columns and index for ``uint`` dtypes (:issue:`48184`)
- Bug in :meth:`DataFrame.loc` coercing dtypes when setting values with a list indexer (:issue:`49159`)
- Bug in :meth:`DataFrame.loc` raising ``ValueError`` with ``bool`` indexer and :class:`MultiIndex` (:issue:`47687`)
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` when right hand side is :class:`DataFrame` with :class:`MultiIndex` columns (:issue:`49121`)
- Bug in :meth:`DataFrame.reindex` casting dtype to ``object`` when :class:`DataFrame` has single extension array column when re-indexing ``columns`` and ``index`` (:issue:`48190`)
- Bug in :func:`~DataFrame.describe` when formatting percentiles in the resulting index showed more decimals than needed (:issue:`46362`)
Expand Down
7 changes: 5 additions & 2 deletions pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1115,9 +1115,12 @@ def _validate_key(self, key, axis: Axis):
# slice of labels (where start-end in labels)
# slice of integers (only if in the labels)
# boolean not in slice and with boolean index
ax = self.obj._get_axis(axis)
if isinstance(key, bool) and not (
is_bool_dtype(self.obj._get_axis(axis))
or self.obj._get_axis(axis).dtype.name == "boolean"
is_bool_dtype(ax)
or ax.dtype.name == "boolean"
or isinstance(ax, MultiIndex)
and is_bool_dtype(ax.get_level_values(0))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if one wanted to index the bools in the second level (and the first level was not boolean), does that take a different code path?

Copy link
Member Author

@phofl phofl Nov 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean something like df.loc[(slice(None), True)]?

This runs through a different path, same reason why df.loc[(True, )] worked already.

We only get there with a scalar indexer, which by definition always refers to the first level

):
raise KeyError(
f"{key}: boolean label can not be used without a boolean index"
Expand Down
18 changes: 18 additions & 0 deletions pandas/tests/frame/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1436,6 +1436,24 @@ def test_loc_rhs_empty_warning(self):
df.loc[:, "a"] = rhs
tm.assert_frame_equal(df, expected)

@pytest.mark.parametrize("indexer", [True, (True,)])
@pytest.mark.parametrize("dtype", [bool, "boolean"])
def test_loc_bool_multiindex(self, dtype, indexer):
# GH#47687
midx = MultiIndex.from_arrays(
[
Series([True, True, False, False], dtype=dtype),
Series([True, False, True, False], dtype=dtype),
],
names=["a", "b"],
)
df = DataFrame({"c": [1, 2, 3, 4]}, index=midx)
result = df.loc[indexer]
expected = DataFrame(
{"c": [1, 2]}, index=Index([True, False], name="b", dtype=dtype)
)
tm.assert_frame_equal(result, expected)


class TestDataFrameIndexingUInt64:
def test_setitem(self, uint64_frame):
Expand Down