Skip to content

Addressing multiindex raises TypeError if indices that are rightmost are not present #20951

Closed
@MasterAir

Description

@MasterAir

Code Sample, a copy-pastable example if possible

import pandas as pd
import numpy as np

A = [100, 100, 200, 200, 300, 300]
B = [10, 10, 20, 21, 31,33]
C = np.random.randint(0, 99, 6)

test_df = pd.DataFrame({'A': A, 'B': B, 'C': C})
test_df = test_df.set_index(['A', 'B'])

print(test_df)
try:
    print(test_df.loc[(100,10)])
except:
    pass

try:
    print(test_df.loc[(0,1)])
except KeyError:
    print('test_df.loc[(0,1)] raises a KeyError')

try:
    print(test_df.loc[(100,1)])
except KeyError as e:
    print(e)
    print('test_df.loc[(100,1)] raises a KeyError')
except TypeError as e:
    print(e)
    print('test+df.loc[(100,1)]) raises a TypeError')

Problem description

If the value is not present in the index, I believe that a KeyError should be raised consistently, so you can write code like.

try:
   df.loc[tuple]
except KeyError:
   # do something if the value isn't present

Expected Output

If df.loc[tuple] does not have a match in the multiindex, a KeyError should be raised.

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.5.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.22.0
pytest: None
pip: 9.0.3
setuptools: 39.0.1
Cython: None
numpy: 1.14.2
scipy: None
pyarrow: None
xarray: None
IPython: None
sphinx: None
patsy: None
dateutil: 2.7.2
pytz: 2018.4
blosc: None
bottleneck: None
tables: None
numexpr: None
feather: None
matplotlib: None
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: None
html5lib: None
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: None
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions