Skip to content

Commit 3df788a

Browse files
committed
BUG: Fix Index.get_level_values() mishandling of boolean, pd.NA, np.nan, and pd.NaT levels
1 parent 188b2da commit 3df788a

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

pandas/_libs/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
__all__ = [
2+
"NA",
23
"Interval",
34
"NaT",
45
"NaTType",
@@ -15,6 +16,7 @@
1516
# see pandas_datetime_exec in pd_datetime.c
1617
import pandas._libs.pandas_parser # isort: skip # type: ignore[reportUnusedImport]
1718
import pandas._libs.pandas_datetime # noqa: F401 # isort: skip # type: ignore[reportUnusedImport]
19+
from pandas._libs.missing import NA
1820
from pandas._libs.interval import Interval
1921
from pandas._libs.tslibs import (
2022
NaT,

pandas/core/indexes/base.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
)
2727

2828
from pandas._libs import (
29+
NA,
2930
NaT,
3031
algos as libalgos,
3132
index as libindex,
@@ -2084,7 +2085,7 @@ def _validate_index_level(self, level) -> None:
20842085
verification must be done like in MultiIndex.
20852086
20862087
"""
2087-
if isinstance(level, int):
2088+
if type(level) is int:
20882089
if level < 0 and level != -1:
20892090
raise IndexError(
20902091
"Too many levels: Index has only 1 level, "
@@ -2094,10 +2095,25 @@ def _validate_index_level(self, level) -> None:
20942095
raise IndexError(
20952096
f"Too many levels: Index has only 1 level, not {level + 1}"
20962097
)
2097-
elif level != self.name:
2098-
raise KeyError(
2099-
f"Requested level ({level}) does not match index name ({self.name})"
2100-
)
2098+
2099+
else:
2100+
if level is NA:
2101+
raise KeyError(
2102+
"Requested level is pandas.NA, which is not a valid index name"
2103+
)
2104+
if level is NaT:
2105+
raise KeyError(
2106+
"Requested level is pandas.NaT, which is not a valid index name"
2107+
)
2108+
if isinstance(level, float) and np.isnan(level):
2109+
raise KeyError(
2110+
"Requested level is NaN, which is not a valid index name"
2111+
)
2112+
2113+
if level != self.name:
2114+
raise KeyError(
2115+
f"Requested level ({level}) does not match index name ({self.name})"
2116+
)
21012117

21022118
def _get_level_number(self, level) -> int:
21032119
self._validate_index_level(level)

0 commit comments

Comments
 (0)