Skip to content

Commit 3793317

Browse files
committed
BUG: Refactor index level validation to improve handling of NA-like values and streamline error messaging
1 parent 703085e commit 3793317

File tree

1 file changed

+10
-23
lines changed

1 file changed

+10
-23
lines changed

pandas/core/indexes/base.py

Lines changed: 10 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2084,48 +2084,35 @@ def _validate_index_level(self, level) -> None:
20842084
verification must be done like in MultiIndex.
20852085
20862086
"""
2087-
# Explicitly raise for missing/null values to match pandas convention
2088-
# Also reject all NA-like values (np.nan, pd.NA, pd.NaT, etc.)
2089-
if isna(level):
2090-
raise KeyError(
2091-
f"Requested level ({level}) does not match index name ({self.name})"
2092-
)
2087+
if isna(level) and isna(self.name):
2088+
return
20932089

2094-
# Handle NA-like index.name as well
2095-
if isna(self.name):
2090+
elif isna(level) or isna(self.name):
20962091
raise KeyError(
20972092
f"Requested level ({level}) does not match index name ({self.name})"
20982093
)
20992094

2100-
# Reject booleans unless the index name is actually a boolean and matches
2101-
if isinstance(level, bool):
2102-
if level != self.name:
2103-
raise KeyError(
2104-
f"Requested level ({level}) does not match index name ({self.name})"
2105-
)
2106-
return
2107-
2108-
# Integer-like levels
2109-
if lib.is_integer(level):
2110-
# Exclude bools (already handled above)
2095+
elif lib.is_integer(level):
21112096
if isinstance(self.name, int) and level == self.name:
21122097
return
21132098
if level < 0 and level != -1:
21142099
raise IndexError(
21152100
f"Too many levels: Index has only 1 level, not {level + 1}"
21162101
)
2102+
elif level > 0:
2103+
raise IndexError(
2104+
f"Too many levels: Index has only 1 level, not {level + 1}"
2105+
)
21172106
return
21182107

2119-
# For string-level, require both to be strings and equal
2120-
if isinstance(level, str) and isinstance(self.name, str):
2108+
elif isinstance(level, str) and isinstance(self.name, str):
21212109
if level != self.name:
21222110
raise KeyError(
21232111
f"Requested level ({level}) does not match index name ({self.name})"
21242112
)
21252113
return
21262114

2127-
# For all other types, require exact match to index name
2128-
if level != self.name:
2115+
elif level != self.name:
21292116
raise KeyError(
21302117
f"Requested level ({level}) does not match index name ({self.name})"
21312118
)

0 commit comments

Comments
 (0)