Skip to content

Commit 4839111

Browse files
alubbock3553x
authored andcommitted
BUG: MultiIndex sort with ascending as list (pandas-dev#16937)
1 parent a077b1f commit 4839111

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

doc/source/whatsnew/v0.21.0.txt

+1
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 :meth:`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

+2-1
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

+23
Original file line numberDiff line numberDiff line change
@@ -2781,3 +2781,26 @@ 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+
# Sort with boolean ascending
2798+
result = s.sort_index(level=['third', 'first'], ascending=False)
2799+
expected = s.iloc[[4, 0, 5, 1, 6, 2, 7, 3]]
2800+
tm.assert_series_equal(result, expected)
2801+
2802+
# Sort with list of boolean ascending
2803+
result = s.sort_index(level=['third', 'first'],
2804+
ascending=[False, True])
2805+
expected = s.iloc[[0, 4, 1, 5, 2, 6, 3, 7]]
2806+
tm.assert_series_equal(result, expected)

0 commit comments

Comments
 (0)