Open renkeven opened 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!
This is due to https://github.com/numpy/numpy/issues/24032
take
Pandas version checks
[X] I have checked that this issue has not already been reported.
[X] 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
Returns
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