Skip to content

BUG: Unknown slicing behavior for Multiindexing when passing through str for int #60104

Open
@renkeven

Description

@renkeven

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

idx_1 = [2000, 2001]
idx_2 = ["a", "b"]
idx_3 = ["x", "y"]

pd.DataFrame(data={"value": range(8)}, index=pd.MultiIndex.from_product([idx_1, idx_2, idx_3])).loc[("2000", "a")]

Returns

   value
x      0
y      1
x      2
y      3

Issue Description

For a number of our dataframe outputs, we have unfortunately mixed the dtypes of year columns as either str or int. This ambiguity means that we get our slicing notation wrong on occasion, which runs risk of returning an incorrect dataframe instead of raising a KeyError.

Following the above example,
Using .loc[("2000", "GIBBERISH")] also returns the same output as the example. I expect KeyError to be raised here as both columns do not exist in the dataframe.
Using .loc["2000"] fails and a KeyError is raised as expected.
Using .loc[("2000",)] returns the same output as .loc[2000], however, here I would expect a KeyError to be raised for the former (the latter returns the desired and correct output).

Expected Behavior

Expect to raise a KeyError, "2000" not in axis here

Installed Versions

INSTALLED VERSIONS

commit : 0691c5c
python : 3.10.15
python-bits : 64
OS : Linux
OS-release : 6.1.100+
Version : #1 SMP PREEMPT_DYNAMIC Sat Aug 24 16:19:44 UTC 2024
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 : 2.2.3
numpy : 1.26.0
pytz : 2024.1
dateutil : 2.9.0
pip : 24.2
Cython : None
sphinx : None
IPython : 8.28.0
adbc-driver-postgresql: None
adbc-driver-sqlite : None
bs4 : 4.12.3
blosc : None
bottleneck : None
dataframe-api-compat : None
fastparquet : None
fsspec : 2024.9.0
html5lib : None
hypothesis : None
gcsfs : 2024.9.0post1
jinja2 : 3.1.4
lxml.etree : 5.3.0
matplotlib : 3.9.2
numba : 0.60.0
numexpr : None
odfpy : None
openpyxl : 3.1.5
pandas_gbq : None
psycopg2 : None
pymysql : None
pyarrow : 15.0.0
pyreadstat : None
pytest : 8.3.3
python-calamine : None
pyxlsb : 1.0.10
s3fs : None
scipy : 1.14.1
sqlalchemy : None
tables : None
tabulate : None
xarray : 2024.9.0
xlrd : 2.0.1
xlsxwriter : 3.2.0
zstandard : 0.23.0
tzdata : 2024.2
qtpy : None
pyqt5 : None

Metadata

Metadata

Labels

BugIndexingRelated to indexing on series/frames, not to indexes themselves

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions