Skip to content

BUG: Accessing a one-level MultiIndex with .loc raises with an unclear error (in 1.4) #45779

Closed
@SdgJlbl

Description

@SdgJlbl

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
df = pd.DataFrame(data=[[0], [1]], index=pd.MultiIndex.from_tuples([('a', ), ('b', )], names=["first",]))
df.loc['a']

Issue Description

Accessing a row of a DataFrame indexed using a MultiIndex with only one level using the loc method raises a ValueError: Cannot remove 1 levels from an index with 1 levels: at least one level must be left..

This change of behaviour does not seem to be listed in the breaking changes section of the changelog, and I haven't find any warning related to this usage in the documentation.

Expected Behavior

With pandas 1.3.5, df.loc['a]` returns the subpart of the DataFrame where the index is 'a':

first  0
a 0

Installed Versions

INSTALLED VERSIONS ------------------ commit : bb1f651 python : 3.9.7.final.0 python-bits : 64 OS : Darwin OS-release : 19.6.0 Version : Darwin Kernel Version 19.6.0: Thu Jan 13 01:26:33 PST 2022; root:xnu-6153.141.51~3/RELEASE_X86_64 machine : x86_64 processor : i386 byteorder : little LC_ALL : None LANG : None LOCALE : None.UTF-8

pandas : 1.4.0
numpy : 1.21.2
pytz : 2021.3
dateutil : 2.8.2
pip : 21.2.4
setuptools : 58.0.4
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.0.2
IPython : 7.29.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : None
numba : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.7.3
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
zstandard : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugIndexingRelated to indexing on series/frames, not to indexes themselvesRegressionFunctionality that used to work in a prior pandas version

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions