Skip to content

ENH: Enable using a boolean loc in a non-boolean index #52102

Open
@alonme

Description

@alonme

Feature Type

  • Adding new functionality to pandas

  • Changing existing functionality in pandas

  • Removing existing functionality in pandas

Problem Description

When using loc to access a boolean value on a DataFrame which has an index that contains both booleans and non-booleans (so the dtype of the index is not bool) an error is raised

import pandas as pd

df = pd.DataFrame({'a': [True, False, "Missing"]}).set_index("a")
df.loc[True]

raises

KeyError: 'True: boolean label can not be used without a boolean index'

I am unsure why this check is performed in _validate_key, but this was an unexpected behavior for me, especially as this works with other combinations of types (int and string for example)

Feature Description

I am not sure why this is currently not supported, so i am unsure if there is a need for a new api or we can use the current one for .loc

Alternative Solutions

df = pd.DataFrame({'a': [True, False, "Missing"]}).set_index("a")
df[df.index == True].loc[True]

This is my current solution, but i don't believe this is a good one

Additional Context

No response

Metadata

Metadata

Assignees

Labels

API DesignEnhancementIndexingRelated to indexing on series/frames, not to indexes themselves

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions