Skip to content

Commit

Permalink
BUG: Fix Index.sort_values with natsort_key raises (pandas-dev#58148)
Browse files Browse the repository at this point in the history
* Add test

* Fix Index.sort_values with natsort_key raises

* Add whatsnew

* Change test without using 3rd party lib

* Change whatsnew
  • Loading branch information
yuanx749 authored Apr 5, 2024
1 parent f4232e7 commit efaaea8
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ Other
- Bug in :func:`unique` on :class:`Index` not always returning :class:`Index` (:issue:`57043`)
- Bug in :meth:`DataFrame.sort_index` when passing ``axis="columns"`` and ``ignore_index=True`` and ``ascending=False`` not returning a :class:`RangeIndex` columns (:issue:`57293`)
- Bug in :meth:`DataFrame.where` where using a non-bool type array in the function would return a ``ValueError`` instead of a ``TypeError`` (:issue:`56330`)
- Bug in :meth:`Index.sort_values` when passing a key function that turns values into tuples, e.g. ``key=natsort.natsort_key``, would raise ``TypeError`` (:issue:`56081`)
- Bug in Dataframe Interchange Protocol implementation was returning incorrect results for data buffers' associated dtype, for string and datetime columns (:issue:`54781`)

.. ***DO NOT USE THIS SECTION***
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ def ensure_key_mapped(
if isinstance(
values, Index
): # convert to a new Index subclass, not necessarily the same
result = Index(result)
result = Index(result, tupleize_cols=False)
else:
# try to revert to original type otherwise
type_of_values = type(values)
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/indexes/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,17 @@ def test_sort_values_with_missing(index_with_missing, na_position, request):
tm.assert_index_equal(result, expected)


def test_sort_values_natsort_key():
# GH#56081
def split_convert(s):
return tuple(int(x) for x in s.split("."))

idx = pd.Index(["1.9", "2.0", "1.11", "1.10"])
expected = pd.Index(["1.9", "1.10", "1.11", "2.0"])
result = idx.sort_values(key=lambda x: tuple(map(split_convert, x)))
tm.assert_index_equal(result, expected)


def test_ndarray_compat_properties(index):
if isinstance(index, PeriodIndex) and not IS64:
pytest.skip("Overflow")
Expand Down

0 comments on commit efaaea8

Please sign in to comment.