Skip to content

API: Use different exception type when MultiIndex indexing fails due to index not being lexsorted #11897

Closed
@Dr-Irv

Description

@Dr-Irv

I'd like to be able to separately trap errors in indexing that are due to the lack of the MultiIndex being lexsorted. Right now, a KeyError is raised, and the only way to tell if the error was due to the lack of a lexsort versus a missing key is to look at the text of the message.

So I'd like to avoid code like this:

try:
    subdf = df.loc['A':'D','Vals']
except KeyError as ker:
    if ker.args[0].startswith("MultiIndex Slicing requires the index to be fully lexsorted"):
        print ("Need to handle fact index not sorted")
    else:
        print ("Need to handle fact that key was missing")

I'd rather write something like:

try:
    subdf = df.loc['A':'D','Vals']
except UnsortedIndexError:
    print ("Need to handle fact index not sorted")
except KeyError:
    print ("Need to handle fact that key was missing")

So could the designers accept a change where a different error is raised in case the index is not lexsorted? If so, I'll implement it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions