Skip to content

Commit 6199347

Browse files
fleimgruberleimgruberf
authored andcommitted
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 3e01c38 commit 6199347

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
@@ -2733,6 +2733,9 @@ def _non_reducing_slice(slice_):
27332733

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

27382741
if not is_list_like(slice_):

pandas/tests/indexing/test_indexing.py

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

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

0 commit comments

Comments
 (0)