Skip to content

BUG: sort_index failing on MultiIndex with label name when key is used #62361

@ldouteau

Description

@ldouteau

Pandas version checks

  • I have checked that this issue has not already been reported.

  • 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 numpy as np
import pandas as pd
from natsort import index_natsorted

df = pd.DataFrame(
    [[1, 2], [3, 4]],
    columns=pd.MultiIndex.from_product([["a"], ["top10", "top2"]], names=("A", "B")),
)
df.sort_index(axis=1, level=1)  # Passes
df.sort_index(axis=1, level="B")  # Passes
df.sort_index(axis=1, level=1, key=lambda x: np.argsort(index_natsorted(x)))  # Passes
df.sort_index(axis=1, level="B", key=lambda x: np.argsort(index_natsorted(x)))  # Fails with KeyError: 'Level B not found'

Issue Description

When sorting over a multi-index with level name and key being set, an error is raised.

Early investigations:

Expected Behavior

sort_index should support both level id or level name

Installed Versions

INSTALLED VERSIONS

commit : c888af6
python : 3.12.10
python-bits : 64
OS : Windows
OS-release : 11
Version : 10.0.22631
machine : AMD64
processor : Intel64 Family 6 Model 140 Stepping 1, GenuineIntel
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : English_United Kingdom.1252

pandas : 2.3.1
numpy : 2.3.2
pytz : 2025.2
dateutil : 2.9.0.post0
pip : None
Cython : None
sphinx : None
IPython : None
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 : 3.10.5
numba : None
numexpr : None
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : None
pyreadstat : None
pytest : None
python-calamine : None
pyxlsb : None
s3fs : None
scipy : 1.16.1
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlsxwriter : None
zstandard : None
tzdata : 2025.2
qtpy : None
pyqt5 : None

Metadata

Metadata

Assignees

Labels

BugMultiIndexNeeds DiscussionRequires discussion from core team before further actionSortinge.g. sort_index, sort_values

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions