Skip to content

Commit efaaea8

Browse files
authored
BUG: Fix Index.sort_values with natsort_key raises (#58148)
* Add test * Fix Index.sort_values with natsort_key raises * Add whatsnew * Change test without using 3rd party lib * Change whatsnew
1 parent f4232e7 commit efaaea8

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

doc/source/whatsnew/v3.0.0.rst

+1
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,7 @@ Other
448448
- Bug in :func:`unique` on :class:`Index` not always returning :class:`Index` (:issue:`57043`)
449449
- 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`)
450450
- 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`)
451+
- 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`)
451452
- Bug in Dataframe Interchange Protocol implementation was returning incorrect results for data buffers' associated dtype, for string and datetime columns (:issue:`54781`)
452453

453454
.. ***DO NOT USE THIS SECTION***

pandas/core/sorting.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ def ensure_key_mapped(
577577
if isinstance(
578578
values, Index
579579
): # convert to a new Index subclass, not necessarily the same
580-
result = Index(result)
580+
result = Index(result, tupleize_cols=False)
581581
else:
582582
# try to revert to original type otherwise
583583
type_of_values = type(values)

pandas/tests/indexes/test_common.py

+11
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,17 @@ def test_sort_values_with_missing(index_with_missing, na_position, request):
479479
tm.assert_index_equal(result, expected)
480480

481481

482+
def test_sort_values_natsort_key():
483+
# GH#56081
484+
def split_convert(s):
485+
return tuple(int(x) for x in s.split("."))
486+
487+
idx = pd.Index(["1.9", "2.0", "1.11", "1.10"])
488+
expected = pd.Index(["1.9", "1.10", "1.11", "2.0"])
489+
result = idx.sort_values(key=lambda x: tuple(map(split_convert, x)))
490+
tm.assert_index_equal(result, expected)
491+
492+
482493
def test_ndarray_compat_properties(index):
483494
if isinstance(index, PeriodIndex) and not IS64:
484495
pytest.skip("Overflow")

0 commit comments

Comments
 (0)