Skip to content
Open
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
26 changes: 22 additions & 4 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2084,16 +2084,34 @@ def _validate_index_level(self, level) -> None:
verification must be done like in MultiIndex.

"""
if isinstance(level, int):
if isna(level) and isna(self.name):
return

elif isna(level) or isna(self.name):
raise KeyError(
f"Requested level ({level}) does not match index name ({self.name})"
)

elif lib.is_integer(level):
if isinstance(self.name, int) and level == self.name:
return
if level < 0 and level != -1:
raise IndexError(
"Too many levels: Index has only 1 level, "
f"{level} is not a valid level number"
f"Too many levels: Index has only 1 level, not {level + 1}"
)
if level > 0:
elif level > 0:
raise IndexError(
f"Too many levels: Index has only 1 level, not {level + 1}"
)
return

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this is a better verification that validates what is expected from the documentation.

Suggested change
elif isinstance(level, str) and isinstance(self.name, str) and level != self.name:
raise KeyError(
f"Requested level ({level}) does not match index name ({self.name})"
)

elif isinstance(level, str) and isinstance(self.name, str):
if level != self.name:
raise KeyError(
f"Requested level ({level}) does not match index name ({self.name})"
)
return

elif level != self.name:
raise KeyError(
f"Requested level ({level}) does not match index name ({self.name})"
Expand Down
Loading