Skip to content

Commit cb9cbba

Browse files
committed
BUG: MultiIndex sort with ascending as list
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 cb9cbba

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

doc/source/whatsnew/v0.21.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ Indexing
156156
- When called on an unsorted ``MultiIndex``, the ``loc`` indexer now will raise ``UnsortedIndexError`` only if proper slicing is used on non-sorted levels (:issue:`16734`).
157157
- Fixes regression in 0.20.3 when indexing with a string on a ``TimedeltaIndex`` (:issue:`16896`).
158158
- Fixed ``TimedeltaIndex.get_loc`` handling of ``np.timedelta64`` inputs (:issue:`16909`).
159+
- Fix MultiIndex ``sort_index`` ordering when ``ascending`` argument is a list but not all levels are specified, or are in a different order (:issue:`16934`).
159160

160161
I/O
161162
^^^

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)