Skip to content

Commit d881247

Browse files
committed
BUG: Improve Index level validation to reject all NA-like values and enhance error handling for boolean levels
1 parent 041994c commit d881247

File tree

1 file changed

+17
-19
lines changed

1 file changed

+17
-19
lines changed

pandas/core/indexes/base.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2085,20 +2085,24 @@ def _validate_index_level(self, level) -> None:
20852085
20862086
"""
20872087
# Explicitly raise for missing/null values to match pandas convention
2088+
# Also reject all NA-like values (np.nan, pd.NA, pd.NaT, etc.)
20882089
if isna(level):
20892090
raise KeyError(
20902091
"Requested level is NA/NaN/NaT, which is not a valid level name"
20912092
)
20922093

2093-
# Standard integer check, but reject bool
2094-
if lib.is_integer(level) and not isinstance(level, bool):
2095-
# If the index itself is named as integer, accept
2096-
if lib.is_integer(self.name) and level == self.name:
2097-
return
2098-
# Only allow 0 and -1 for a single-level Index
2099-
if level in (0, -1):
2100-
return
2101-
if level < 0:
2094+
# Reject booleans unless the index name is actually a boolean and matches
2095+
if isinstance(level, bool):
2096+
if level != self.name:
2097+
raise KeyError(
2098+
f"Requested level ({level}) does not match index name ({self.name})"
2099+
)
2100+
return
2101+
2102+
# Integer-like levels
2103+
if lib.is_integer(level):
2104+
# Exclude bools (already handled above)
2105+
if level < 0 and level != -1:
21022106
raise IndexError(
21032107
"Too many levels: Index has only 1 level, "
21042108
f"{level} is not a valid level number"
@@ -2107,21 +2111,15 @@ def _validate_index_level(self, level) -> None:
21072111
raise IndexError(
21082112
f"Too many levels: Index has only 1 level, not {level + 1}"
21092113
)
2114+
return
21102115

2111-
# String level: only match if name is exactly the same string
2112-
elif isinstance(level, str) and not (
2113-
isinstance(self.name, str) and level == self.name
2114-
):
2116+
# For all other types, require exact match to index name
2117+
# Use pandas' isna for both level and self.name to catch NA-like names
2118+
if isna(self.name) or level != self.name:
21152119
raise KeyError(
21162120
f"Requested level ({level}) does not match index name ({self.name})"
21172121
)
21182122

2119-
# If level type is not int, str, or is NA, always raise KeyError
2120-
else:
2121-
raise KeyError(
2122-
f"Requested level ({level}) is not a valid level name or number"
2123-
)
2124-
21252123
def _get_level_number(self, level) -> int:
21262124
self._validate_index_level(level)
21272125
return 0

0 commit comments

Comments
 (0)