Skip to content

Commit 4f1551c

Browse files
committed
BUG: Fix boolean column indexing (#61980)
1 parent f9f62a3 commit 4f1551c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

pandas/core/frame.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3995,6 +3995,15 @@ def __getitem__(self, key):
39953995
key = lib.item_from_zerodim(key)
39963996
key = com.apply_if_callable(key, self)
39973997

3998+
if (
3999+
isinstance(key, (list, np.ndarray))
4000+
and len(key) > 0
4001+
and any(isinstance(k, bool) for k in key)
4002+
and all(isinstance(k, (bool, str)) for k in key)
4003+
and not (len(key) == len((self.index) and all(isinstance(k, bool) for k in key)))
4004+
):
4005+
return self.reindex_columns(key)
4006+
39984007
if is_hashable(key) and not is_iterator(key) and not isinstance(key, slice):
39994008
# is_iterator to exclude generator e.g. test_getitem_listlike
40004009
# As of Python 3.12, slice is hashable which breaks MultiIndex (GH#57500)

pandas/tests/frame/indexing/test_getitem.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,14 @@ def test_getitem_list_duplicates(self):
101101
expected = df.iloc[:, 2:]
102102
tm.assert_frame_equal(result, expected)
103103

104+
def test_getitem_bool_column_name(self):
105+
# GH#61980
106+
data = {"A": [1, 2, 3], "B": [4, 5, 6], True: [7, 8, 9]}
107+
df = DataFrame(data)
108+
result = df[[True]]
109+
expected = DataFrame({True: [7, 8, 9]})
110+
tm.assert_frame_equal(result, expected)
111+
104112
def test_getitem_dupe_cols(self):
105113
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
106114
msg = "\"None of [Index(['baf'], dtype="

0 commit comments

Comments
 (0)