Description
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 pandas as pd
ind= pd.MultiIndex.from_arrays([['B', 'C', 'A', 'A'],
['H', 'G', 'F', 'G'],
['V', 'U', 'W', 'U']])
ind = ind.set_levels(['B','M','A'], level=0)
ind.sortlevel(0, sort_remaining=True)
Issue Description
Result is not sorted:
(MultiIndex([('B', 'F', 'W'),
('B', 'G', 'U'),
('M', 'H', 'V'),
('A', 'G', 'U')],
),
array([2, 3, 0, 1]))
Expected Behavior
MultiIndex should be sorted. Cryptic phrase in documentation: "The result will respect the original ordering of the associated factor at that level." is not productive. A function called sortlevel
should not depend on some mysterious "original ordering of an associated factor at that level".
If anything, please rename the function to: sortlevel_based_on_original_ordering_of_the_associated_factor_at_that_level
, otherwise people will be confused that it's not working. Also, what the "original ordering of the associated factor at that level" is, is nowhere discussed. Also, for consistency reasons, the function should be called: sort_level
(or sort_levels
?) not sortlevel
.
Installed Versions
INSTALLED VERSIONS
commit : 87cfe4e
python : 3.9.13.final.0
python-bits : 64
OS : Darwin
OS-release : 20.6.0
Version : Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8
pandas : 1.5.0
numpy : 1.22.4
pytz : 2022.1
dateutil : 2.8.2
setuptools : 63.1.0
pip : 22.1.2
Cython : None
pytest : None
hypothesis : None
sphinx : 5.0.2
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.0
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.4.0
pandas_datareader: None
bs4 : 4.11.1
bottleneck : 1.3.4
brotli : 1.0.9
fastparquet : 0.8.1
fsspec : 2022.5.0
gcsfs : None
matplotlib : 3.5.2
numba : 0.55.2
numexpr : 2.8.3
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : 8.0.0
pyreadstat : None
pyxlsb : None
s3fs : 2022.5.0
scipy : 1.8.1
snappy : None
sqlalchemy : None
tables : None
tabulate : 0.8.10
xarray : 2022.3.0
xlrd : 2.0.1
xlwt : None
zstandard : None
tzdata : 2022.1