Skip to content

Commit 561da9f

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 2c1a398 commit 561da9f

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

21702170
def pred(part):
21712171
# true when slice does *not* reduce
2172+
# False when part is a tuple, i.e. MultiIndex slice
2173+
if isinstance(part, tuple):
2174+
return False
21722175
return isinstance(part, slice) or is_list_like(part)
21732176

21742177
if not is_list_like(slice_):

pandas/tests/indexing/test_indexing.py

+15
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,21 @@ def test_non_reducing_slice(self):
846846
tslice_ = _non_reducing_slice(slice_)
847847
assert isinstance(df.loc[tslice_], DataFrame)
848848

849+
def test_non_reducing_slice_on_multiindex(self):
850+
dic = {
851+
('a', 'd'): [1, 4],
852+
('a', 'c'): [2, 3],
853+
('b', 'c'): [3, 2],
854+
('b', 'd'): [4, 1]
855+
}
856+
857+
df = pd.DataFrame(dic, index=[0, 1])
858+
idx = pd.IndexSlice
859+
860+
slice_ = idx[:, idx['b', 'd']]
861+
tslice_ = _non_reducing_slice(slice_)
862+
assert isinstance(df.loc[tslice_], DataFrame)
863+
849864
def test_list_slice(self):
850865
# like dataframe getitem
851866
slices = [['A'], Series(['A']), np.array(['A'])]

0 commit comments

Comments
 (0)