Pandas version checks
-
[x] I have checked that this issue has not already been reported.
-
[x] I have confirmed this bug exists on the latest version of pandas.
-
[ ] I have confirmed this bug exists on the main branch of pandas.
Reproducible Example
import pandas as pd
pd.Index([], name=True).get_level_values(level=True)
Issue Description
I get IndexError: Too many levels: Index has only 1 level, not 2
. Also, pd.Index([], name=True).get_level_values(level=False)
should raise KeyError
, but it returns the whole index.
Also, name np.nan
, pd.NA
or pd.NaT
causes KeyError: 'Requested level (nan) does not match index name (nan)'
.
Expected Behavior
I should get the whole index from get_level_values(True)
Installed Versions
Comment From: Alvaro-Kothe
The issue stems from the _validate_index_level
function:
https://github.com/pandas-dev/pandas/blob/4665c10899bc413b639194f6fb8665a5c70f7db5/pandas/core/indexes/base.py#L2000-L2021
The problem arises because isinstance(False, int)
and isinstance(True, int)
both return True
. Additionally, the inequality check evaluates to True
for np.nan
and pd.NaT
, though I expected a distinct error for pd.NA
.
Anyway, since get_level_values
is essentially a no-op for Index
, addressing edge cases for non-string names doesn’t seem worth the effort.