Skip to content

Commit 411d31c

Browse files
committed
Include MultiIndex slice in non-reducing slices
Changes behaviour of user-passed IndexSlice to return DataFrame instead of reducing to Series. MultiIndex slices are tuples so this explicitly checks type and guards with parentheses. Fixes pandas-dev#19861
1 parent 9019582 commit 411d31c

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

pandas/core/indexing.py

+3
Original file line numberDiff line numberDiff line change
@@ -2734,6 +2734,9 @@ def _non_reducing_slice(slice_):
27342734

27352735
def pred(part):
27362736
# true when slice does *not* reduce
2737+
# False when part is a tuple, i.e. MultiIndex slice
2738+
if isinstance(part, tuple):
2739+
return False
27372740
return isinstance(part, slice) or is_list_like(part)
27382741

27392742
if not is_list_like(slice_):

pandas/tests/indexing/test_indexing.py

+15
Original file line numberDiff line numberDiff line change
@@ -902,6 +902,21 @@ def test_non_reducing_slice(self):
902902
tslice_ = _non_reducing_slice(slice_)
903903
assert isinstance(df.loc[tslice_], DataFrame)
904904

905+
def test_non_reducing_slice_on_multiindex(self):
906+
dic = {
907+
('a', 'd'): [1, 4],
908+
('a', 'c'): [2, 3],
909+
('b', 'c'): [3, 2],
910+
('b', 'd'): [4, 1]
911+
}
912+
913+
df = pd.DataFrame(dic, index=[0, 1])
914+
idx = pd.IndexSlice
915+
916+
slice_ = idx[:, idx['b', 'd']]
917+
tslice_ = _non_reducing_slice(slice_)
918+
assert isinstance(df.loc[tslice_], DataFrame)
919+
905920
def test_list_slice(self):
906921
# like dataframe getitem
907922
slices = [['A'], Series(['A']), np.array(['A'])]

0 commit comments

Comments
 (0)