Skip to content

Commit 09e2b6f

Browse files
committed
Fix MultiIndex sort with mixed ascending argument
MultiIndex sorting with `sort_index` would fail when the `ascending` argument was specified as a list but not all levels of the index were specified in the `level` argument, or the levels were specified in a different order to the MultiIndex. This PR rectifies the issue and introduces a unit test based on pandas-dev#16934 Fixes: pandas-dev#16934
1 parent ad24759 commit 09e2b6f

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

pandas/core/indexes/multi.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1697,7 +1697,8 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True):
16971697
raise ValueError("level must have same length as ascending")
16981698

16991699
from pandas.core.sorting import lexsort_indexer
1700-
indexer = lexsort_indexer(self.labels, orders=ascending)
1700+
indexer = lexsort_indexer([self.labels[lev] for lev in level],
1701+
orders=ascending)
17011702

17021703
# level ordering
17031704
else:

pandas/tests/test_multilevel.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2781,3 +2781,20 @@ def test_sort_index_nan(self):
27812781
result = s.sort_index(na_position='first')
27822782
expected = s.iloc[[1, 2, 3, 0]]
27832783
tm.assert_series_equal(result, expected)
2784+
2785+
def test_sort_ascending_list(self):
2786+
# GH: 16934
2787+
2788+
# Set up a Series with a three level MultiIndex
2789+
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
2790+
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],
2791+
[4, 3, 2, 1, 4, 3, 2, 1]]
2792+
tuples = list(zip(*arrays))
2793+
index = pd.MultiIndex.from_tuples(tuples,
2794+
names=['first', 'second', 'third'])
2795+
s = pd.Series(range(8), index=index)
2796+
2797+
result = s.sort_index(level=['third', 'first'],
2798+
ascending=[False, True])
2799+
2800+
assert np.array_equal(result, [0, 4, 1, 5, 2, 6, 3, 7])

0 commit comments

Comments
 (0)