pandas-dev / pandas

Flexible and powerful data analysis / manipulation library for Python, providing labeled data structures similar to R data.frame objects, statistical functions, and much more
https://pandas.pydata.org
BSD 3-Clause "New" or "Revised" License
43.71k stars 17.92k forks source link

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

Open renkeven opened 1 week ago

renkeven commented 1 week ago

Pandas version checks

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 : 0691c5cf90477d3503834d983f69350f250a6ff7 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

rhshadrach commented 1 week ago

Thanks for the report. Indeed, this is not intentional. The following example raises a KeyError:

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

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

When the index is sorted, pandas uses NumPy's searchsorted, which has what I think is a somewhat surprising result.

arr = np.array([2000, 2000, 2000, 2001, 2001, 2001, 2001])
print(arr.searchsorted("2001", side="left"))
# 3

Further investigations and PRs to fix are welcome!

rhshadrach commented 1 week ago

This is due to https://github.com/numpy/numpy/issues/24032

AshmitGupta commented 2 days ago

take