Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -4533,6 +4533,8 @@ def sort_index(

inplace = validate_bool_kwarg(inplace, "inplace")
axis = self._get_axis_number(axis)
ascending = validate_ascending(ascending)

target = self._get_axis(axis)

indexer = get_indexer_indexer(
Expand Down Expand Up @@ -11772,3 +11774,25 @@ def _doc_params(cls):
The required number of valid values to perform the operation. If fewer than
``min_count`` non-NA values are present the result will be NA.
"""


def validate_ascending(
ascending: Union[bool, Sequence[bool]],
) -> Union[bool, Sequence[bool]]:
"""Validate ``ascending`` kwargs for ``sort_index`` method."""
if not isinstance(ascending, (list, tuple)):
_check_ascending_element(ascending)
return ascending

for item in ascending:
_check_ascending_element(item)
return ascending


def _check_ascending_element(value):
"""Ensure that each item in ``ascending`` kwarg is either bool or int."""
if (
value is None
or not isinstance(value, (bool, int))
):
raise ValueError("ascending must be either a bool or a sequence of bools")
16 changes: 16 additions & 0 deletions pandas/tests/frame/methods/test_sort_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,22 @@ def test_sort_index_with_categories(self, categories):
)
tm.assert_frame_equal(result, expected)

@pytest.mark.parametrize(
"ascending",
[
None,
(True, None),
(False, 'True'),
],
)
def test_sort_index_ascending_bad_value_raises(self, ascending):
df = DataFrame(np.arange(64))
length = len(df.index)
df.index = [(i - length / 2) % length for i in range(length)]
match = "ascending must be either a bool or a sequence of bools"
with pytest.raises(ValueError, match=match):
df.sort_index(axis=0, ascending=ascending, na_position="first")


class TestDataFrameSortIndexKey:
def test_sort_multi_index_key(self):
Expand Down
14 changes: 14 additions & 0 deletions pandas/tests/series/methods/test_sort_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,20 @@ def test_sort_index_ascending_list(self):
expected = ser.iloc[[0, 4, 1, 5, 2, 6, 3, 7]]
tm.assert_series_equal(result, expected)

@pytest.mark.parametrize(
"ascending",
[
None,
(True, None),
(False, 'True'),
],
)
def test_sort_index_ascending_bad_value_raises(self, ascending):
ser = Series(range(10), index=[0, 3, 2, 1, 4, 5, 7, 6, 8, 9])
match = "ascending must be either a bool or a sequence of bools"
with pytest.raises(ValueError, match=match):
ser.sort_index(ascending=ascending)


class TestSeriesSortIndexKey:
def test_sort_index_multiindex_key(self):
Expand Down