Skip to content

Commit

Permalink
BUG MultiIndex sort with mixed ascending argument
Browse files Browse the repository at this point in the history
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
  • Loading branch information
alubbock committed Jul 15, 2017
1 parent ad24759 commit cad3f53
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1697,7 +1697,8 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True):
raise ValueError("level must have same length as ascending")

from pandas.core.sorting import lexsort_indexer
indexer = lexsort_indexer(self.labels, orders=ascending)
indexer = lexsort_indexer([self.labels[lev] for lev in level],
orders=ascending)

# level ordering
else:
Expand Down
17 changes: 17 additions & 0 deletions pandas/tests/test_multilevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2781,3 +2781,20 @@ def test_sort_index_nan(self):
result = s.sort_index(na_position='first')
expected = s.iloc[[1, 2, 3, 0]]
tm.assert_series_equal(result, expected)

def test_sort_ascending_list(self):
# GH: 16934

# Set up a Series with a three level MultiIndex
arrays = [['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'],
['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'],
[4, 3, 2, 1, 4, 3, 2, 1]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples,
names=['first', 'second', 'third'])
s = pd.Series(range(8), index=index)

result = s.sort_index(level=['third', 'first'],
ascending=[False, True])

assert np.array_equal(result, [0, 4, 1, 5, 2, 6, 3, 7])

0 comments on commit cad3f53

Please sign in to comment.