Skip to content

Commit bc70099

Browse files
BUG: Using boolean keys to select a column (GH44322) (#44425)
1 parent 5cdde87 commit bc70099

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

doc/source/whatsnew/v1.4.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -607,7 +607,7 @@ Indexing
607607
- Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`)
608608
- Bug in :meth:`Series.__setitem__` with a boolean mask indexer setting a listlike value of length 1 incorrectly broadcasting that value (:issue:`44265`)
609609
- Bug in :meth:`DataFrame.loc.__setitem__` and :meth:`DataFrame.iloc.__setitem__` with mixed dtypes sometimes failing to operate in-place (:issue:`44345`)
610-
-
610+
- Bug in :meth:`DataFrame.loc.__getitem__` incorrectly raising ``KeyError`` when selecting a single column with a boolean key (:issue:`44322`).
611611

612612
Missing
613613
^^^^^^^

pandas/core/indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -994,7 +994,7 @@ def _validate_key(self, key, axis: int):
994994
# slice of labels (where start-end in labels)
995995
# slice of integers (only if in the labels)
996996
# boolean not in slice and with boolean index
997-
if isinstance(key, bool) and not is_bool_dtype(self.obj.index):
997+
if isinstance(key, bool) and not is_bool_dtype(self.obj._get_axis(axis)):
998998
raise KeyError(
999999
f"{key}: boolean label can not be used without a boolean index"
10001000
)

pandas/tests/indexing/test_loc.py

+20
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,26 @@ def test_column_types_consistent(self):
178178
)
179179
tm.assert_frame_equal(df, expected)
180180

181+
@pytest.mark.parametrize(
182+
"obj, key, exp",
183+
[
184+
(
185+
DataFrame([[1]], columns=Index([False])),
186+
IndexSlice[:, False],
187+
Series([1], name=False),
188+
),
189+
(Series([1], index=Index([False])), False, [1]),
190+
(DataFrame([[1]], index=Index([False])), False, Series([1], name=False)),
191+
],
192+
)
193+
def test_loc_getitem_single_boolean_arg(self, obj, key, exp):
194+
# GH 44322
195+
res = obj.loc[key]
196+
if isinstance(exp, (DataFrame, Series)):
197+
tm.assert_equal(res, exp)
198+
else:
199+
assert res == exp
200+
181201

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

0 commit comments

Comments
 (0)