Skip to content

Commit d6c157c

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 d6c157c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-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

+14
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,20 @@ 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 = {('a', 'd'): [1, 4],
851+
('a', 'c'): [2, 3],
852+
('b', 'c'): [3, 2],
853+
('b', 'd'): [4, 1],
854+
}
855+
856+
df = pd.DataFrame(dic, index=[0, 1])
857+
idx = pd.IndexSlice
858+
859+
slice_ = idx[:, idx['b', 'd']]
860+
tslice_ = _non_reducing_slice(slice_)
861+
assert isinstance(df.loc[tslice_], DataFrame)
862+
849863
def test_list_slice(self):
850864
# like dataframe getitem
851865
slices = [['A'], Series(['A']), np.array(['A'])]

0 commit comments

Comments
 (0)