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
import pandas as pd
idx = pd.IndexSlice
index = pd.MultiIndex.from_tuples(
[("a", "b", "c"), ("a", "a", "c"), ("a", "c", "b")],
names=["col1", "col2", "col3"]
)
df = pd.DataFrame(index=index, data={"value": [1, 2, 3]})
# works and returns empty dataframe (for every key, that is not in the level "col2")
df.loc[idx[:, ["a"], ["somekey"]]]
# raises KeyError (for every key given for level "col2" that is available in that level, but not in the given combination of keys.
# If the above is itended (returning empty DataFrame), then this should return an empty DataFrame as well
df.loc[idx[:, ["a"], ["b"]]]
Issue Description
See reproducible example.
To fix that the lines
https://github.com/pandas-dev/pandas/blob/c35eca35d6070ea508a115ef1008ab40f33ed727/pandas/core/indexes/multi.py#L3290-L3291
should not raise an Exception but return
np.array([], dtype=np.intp)
like when an item cannot be found in the current index level:
https://github.com/pandas-dev/pandas/blob/c35eca35d6070ea508a115ef1008ab40f33ed727/pandas/core/indexes/multi.py#L3269-L3272
Expected Behavior
return an empty dataframe, if the combination of keys in the levels is not available.
>>> df.loc[idx[:, ["a"], ["b"]]]
Empty DataFrame
Columns: [value]
Index: []
Installed Versions
Comment From: fwitte
My bad, I confused the pandas installations in my environment and the clone repository. I guess #42351 dealt with it, although I'd have preferred the other way round :(.
Thanks and have a nice weekend!
Comment From: phofl
Closing then