Skip to content

Commit 540471b

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 cf92230 commit 540471b

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
@@ -812,6 +812,21 @@ def test_non_reducing_slice(self):
812812
tslice_ = _non_reducing_slice(slice_)
813813
assert isinstance(df.loc[tslice_], DataFrame)
814814

815+
def test_non_reducing_slice_on_multiindex(self):
816+
dic = {
817+
('a', 'd'): [1, 4],
818+
('a', 'c'): [2, 3],
819+
('b', 'c'): [3, 2],
820+
('b', 'd'): [4, 1]
821+
}
822+
823+
df = pd.DataFrame(dic, index=[0, 1])
824+
idx = pd.IndexSlice
825+
826+
slice_ = idx[:, idx['b', 'd']]
827+
tslice_ = _non_reducing_slice(slice_)
828+
assert isinstance(df.loc[tslice_], DataFrame)
829+
815830
def test_list_slice(self):
816831
# like dataframe getitem
817832
slices = [['A'], Series(['A']), np.array(['A'])]

0 commit comments

Comments
 (0)