Skip to content

BUG: Subindexing on the second level datetime index caused key error #54305

@3zhang

Description

@3zhang

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

tb1 = pd.DataFrame({'date': pd.date_range('2017-01-01', '2020-12-31')})
tb2 = pd.DataFrame({'cat': ['a', 'b', 'c']})

tb3 = tb2.merge(tb1, 'cross')
tb3['value'] = 1
tb3.set_index(['cat', 'date'], inplace=True)

tb3.loc[('a', '2017')]
#No error
tb3.loc[(slice(None), '2017')]
#KeyError: '2017'

Issue Description

Subindexing on a multiindex with second level datetime index sometimes caused error. Specifically, when trying to skip the first level and subindexing the second datetime level.

Expected Behavior

Should return the expected subset dataframe

Installed Versions

pandas : 1.5.3
numpy : 1.23.5
pytz : 2023.3
dateutil : 2.8.2
setuptools : 67.6.1
pip : 23.0.1
Cython : 0.29.33
pytest : None
hypothesis : None
sphinx : 6.1.3
blosc : None
feather : None
xlsxwriter : None
lxml.etree : 4.9.2
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 3.1.2
IPython : 8.10.0
pandas_datareader: None
bs4 : 4.12.0
bottleneck : None
brotli :
fastparquet : None
fsspec : None
gcsfs : None
matplotlib : 3.7.1
numba : 0.56.4
numexpr : None
odfpy : None
openpyxl : 3.0.10
pandas_gbq : None
pyarrow : None
pyreadstat : None
pyxlsb : None
s3fs : None
scipy : 1.10.1
snappy : None
sqlalchemy : 2.0.12
tables : None
tabulate : None
xarray : 2023.3.0
xlrd : 2.0.1
xlwt : None
zstandard : None
tzdata : 2023.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugClosing CandidateMay be closeable, needs more eyeballsIndexingRelated to indexing on series/frames, not to indexes themselvesMultiIndex

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions