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

------------------ commit : 4665c10899bc413b639194f6fb8665a5c70f7db5 python : 3.13.5 python-bits : 64 OS : Darwin OS-release : 24.6.0 Version : Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:30 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6020 machine : arm64 processor : arm byteorder : little LC_ALL : None LANG : en_US.UTF-8 LOCALE : en_US.UTF-8 pandas : 2.3.2 numpy : 2.3.2 pytz : 2025.2 dateutil : 2.9.0.post0 pip : 25.1 Cython : None sphinx : None IPython : 9.4.0 adbc-driver-postgresql: None adbc-driver-sqlite : None bs4 : None blosc : None bottleneck : None dataframe-api-compat : None fastparquet : None fsspec : None html5lib : None hypothesis : None gcsfs : None jinja2 : None lxml.etree : None matplotlib : None numba : None numexpr : None odfpy : None openpyxl : None pandas_gbq : None psycopg2 : None pymysql : None pyarrow : None pyreadstat : None pytest : None python-calamine : None pyxlsb : None s3fs : None scipy : None sqlalchemy : None tables : None tabulate : None xarray : None xlrd : None xlsxwriter : None zstandard : None tzdata : 2025.2 qtpy : None pyqt5 : None

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.