Skip to content

BUG: Using boolean keys to select a column (GH44322) #44425

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 3 commits into from
Nov 15, 2021
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/v1.4.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ Indexing
- Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`)
- Bug in :meth:`Series.__setitem__` with a boolean mask indexer setting a listlike value of length 1 incorrectly broadcasting that value (:issue:`44265`)
- Bug in :meth:`DataFrame.loc.__setitem__` and :meth:`DataFrame.iloc.__setitem__` with mixed dtypes sometimes failing to operate in-place (:issue:`44345`)
-
- Bug in :meth:`DataFrame.loc.__getitem__` incorrectly raising ``KeyError`` when selecting a single column with a boolean key (:issue:`44322`).

Missing
^^^^^^^
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -994,7 +994,7 @@ def _validate_key(self, key, axis: int):
# slice of labels (where start-end in labels)
# slice of integers (only if in the labels)
# boolean not in slice and with boolean index
if isinstance(key, bool) and not is_bool_dtype(self.obj.index):
if isinstance(key, bool) and not is_bool_dtype(self.obj._get_axis(axis)):
raise KeyError(
f"{key}: boolean label can not be used without a boolean index"
)
Expand Down
20 changes: 20 additions & 0 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,26 @@ def test_column_types_consistent(self):
)
tm.assert_frame_equal(df, expected)

@pytest.mark.parametrize(
"obj, key, exp",
[
(
DataFrame([[1]], columns=Index([False])),
IndexSlice[:, False],
Series([1], name=False),
),
(Series([1], index=Index([False])), False, [1]),
(DataFrame([[1]], index=Index([False])), False, Series([1], name=False)),
],
)
def test_loc_getitem_single_boolean_arg(self, obj, key, exp):
# GH 44322
res = obj.loc[key]
if isinstance(exp, (DataFrame, Series)):
tm.assert_equal(res, exp)
else:
assert res == exp


class TestLoc2:
# TODO: better name, just separating out things that rely on base class
Expand Down