Skip to content

MultiIndex.get_loc throws KeyError under specific circumstances #30053

Closed
@p-himik

Description

@p-himik

Code Sample, a copy-pastable example if possible

from pandas import MultiIndex

key = ('a', 7)
idx = MultiIndex(levels=[['a'], [0, 7], [1]],
                 codes=[[0, 0], [1, 0], [0, 0]],
                 names=['x', 'y', 'z'],
                 sortorder=0)

idx.get_loc(key)

Problem description

Executing the above code results in

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-26c5d4d0888a> in <module>
----> 1 idx.get_loc(key)

~/soft/miniconda3/envs/junk/lib/python3.7/site-packages/pandas/core/indexes/multi.py in get_loc(self, key, method)
   2696 
   2697         if start == stop:
-> 2698             raise KeyError(key)
   2699 
   2700         if not follow_key:

KeyError: ('a', 1, 2)

Note that the exception disappears if you do any of the following:

  • change sortorder to None
  • change the codes of level 1 to [0, 1]
  • change the values of level 1 to [0, 7]
  • completely remove level 2

Expected Output

I don't think there should be any exception here since the way I created the index appears to be valid, and the key is definitely in there.

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.7.1.final.0
python-bits : 64
OS : Linux
OS-release : 5.3.0-23-generic
machine : x86_64
processor : x86_64
byteorder : little
LC_ALL : en_US.UTF-8
LANG : en_US.UTF-8
LOCALE : en_US.UTF-8

pandas : 0.25.3
numpy : 1.15.4
pytz : 2018.9
dateutil : 2.7.5
pip : 18.1
setuptools : 40.6.3
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.10
IPython : 7.2.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : 3.0.2
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    IndexingRelated to indexing on series/frames, not to indexes themselvesMultiIndexNeeds TestsUnit test(s) needed to prevent regressions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions