Skip to content

Commit

Permalink
BUG: Index sortlevel ascending add type checking pandas-dev#32334
Browse files Browse the repository at this point in the history
  • Loading branch information
beanan committed Oct 1, 2020
1 parent 1d29bf0 commit 2d67be4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
14 changes: 14 additions & 0 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,20 @@ def sortlevel(self, level=None, ascending=True, sort_remaining=None):
-------
Index
"""
if not isinstance(ascending, (list, bool)):
raise TypeError(
"ascending must be a single bool value or"
"a list of bool values of length 1"
)

if isinstance(ascending, list):
if len(ascending) > 1:
raise TypeError("ascending must be a list of bool values of length 1")
ascending = ascending[0]

if not isinstance(ascending, bool):
raise TypeError("ascending must be a bool value")

return self.sort_values(return_indexer=True, ascending=ascending)

def _get_level_values(self, level):
Expand Down
25 changes: 25 additions & 0 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2222,6 +2222,31 @@ def test_contains_method_removed(self, index):
with pytest.raises(AttributeError, match=msg):
index.contains(1)

def test_sortlevel(self):
index = pd.Index([5, 4, 3, 2, 1])
with pytest.raises(Exception, match="ascending must be a single bool value or"):
index.sortlevel(ascending="True")

with pytest.raises(
Exception, match="ascending must be a list of bool values of length 1"
):
index.sortlevel(ascending=[True, True])

with pytest.raises(Exception, match="ascending must be a bool value"):
index.sortlevel(ascending=["True"])

expected = pd.Index([1, 2, 3, 4, 5])
result = index.sortlevel(ascending=[True])
tm.assert_index_equal(result[0], expected)

expected = pd.Index([1, 2, 3, 4, 5])
result = index.sortlevel(ascending=True)
tm.assert_index_equal(result[0], expected)

expected = pd.Index([5, 4, 3, 2, 1])
result = index.sortlevel(ascending=False)
tm.assert_index_equal(result[0], expected)


class TestMixedIntIndex(Base):
# Mostly the tests from common.py for which the results differ
Expand Down

0 comments on commit 2d67be4

Please sign in to comment.