Skip to content

ENH: specify missing keys in KeyError when passing list-like to .loc #34272

Closed
@arredond

Description

@arredond

I'm a big fan of the strong limitation when passing list-likes to .loc[]. However, when the a key is missing and the KeyError is raised, it'd be helpful to know which key/s is/are missing.

I understand this could have performance implications since each key of the list-like object should be searched, but also think the UX would be improved.

At least, the first missing key could be reported, without hindering performance. I'm happy to provide a PR for this if provided with some guidelines (I suppose this affects both Series and DataFrames, as well as maybe some other parts of the code I'm not aware of).

pd.__version__
# '1.0.3'

s = pd.Series({'a': 1, 'b': 2, 'c': 3})
s.loc['d'] # Raises KeyError but specifies 'd' is missing
s.loc[['a', 'b', 'c', 'd']] # Raises KeyError without specifying which key is missing

Metadata

Metadata

Assignees

No one assigned

    Labels

    Error ReportingIncorrect or improved errors from pandas

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions