Skip to content

BUG: Fix boolean column indexing for DataFrame (#61980) #61982

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

Closed
wants to merge 13 commits into from
Closed
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
11 changes: 11 additions & 0 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3995,6 +3995,17 @@ def __getitem__(self, key):
key = lib.item_from_zerodim(key)
key = com.apply_if_callable(key, self)

if (
isinstance(key, (list, np.ndarray))
and len(key) > 0
and any(isinstance(k, bool) for k in key)
and all(isinstance(k, (bool, str)) for k in key)
and not (
len(key) == len(self.index) and all(isinstance(k, bool) for k in key)
)
):
return self.reindex_columns(key)

if is_hashable(key) and not is_iterator(key) and not isinstance(key, slice):
# is_iterator to exclude generator e.g. test_getitem_listlike
# As of Python 3.12, slice is hashable which breaks MultiIndex (GH#57500)
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/frame/indexing/test_getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,13 @@ def test_getitem_list_duplicates(self):
expected = df.iloc[:, 2:]
tm.assert_frame_equal(result, expected)

def test_getitem_single_bool_column(self):
# GH#61980
df = DataFrame({True: [10, 20, 30]})
result = df[[True]]
expected = DataFrame({True: [10, 20, 30]})
tm.assert_frame_equal(result, expected)

def test_getitem_dupe_cols(self):
df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"])
msg = "\"None of [Index(['baf'], dtype="
Expand Down
Loading