Skip to content

Commit 61ff633

Browse files
DOC: updated inline documentation for key sorting
1 parent af949fd commit 61ff633

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

pandas/core/frame.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -4798,9 +4798,8 @@ def sort_index(
47984798
elif isinstance(labels, ABCMultiIndex):
47994799
from pandas.core.sorting import lexsort_indexer
48004800

4801-
codes = labels._get_codes_for_sorting()
48024801
indexer = lexsort_indexer(
4803-
codes,
4802+
labels._get_codes_for_sorting(),
48044803
orders=ascending,
48054804
na_position=na_position,
48064805
)

pandas/core/series.py

+36-2
Original file line numberDiff line numberDiff line change
@@ -2858,6 +2858,9 @@ def sort_values(
28582858
na_position : {'first' or 'last'}, default 'last'
28592859
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
28602860
the end.
2861+
key : function, default None
2862+
If not None, apply the key function to every value before
2863+
sorting. Identical to key argument in built-in sorted function.
28612864
28622865
Returns
28632866
-------
@@ -2940,6 +2943,22 @@ def sort_values(
29402943
2 d
29412944
0 z
29422945
dtype: object
2946+
2947+
>>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
2948+
>>> s.sort_values()
2949+
1 B
2950+
3 D
2951+
0 a
2952+
2 c
2953+
4 e
2954+
dtype: object
2955+
>>> s.sort_values(key=str.lower)
2956+
0 a
2957+
1 B
2958+
2 c
2959+
3 D
2960+
4 e
2961+
dtype: object
29432962
"""
29442963
inplace = validate_bool_kwarg(inplace, "inplace")
29452964
# Validate the axis parameter
@@ -3045,6 +3064,9 @@ def sort_index(
30453064
sort_remaining : bool, default True
30463065
If True and sorting by level and index is multilevel, sort by other
30473066
levels too (in order) after sorting by specified level.
3067+
key : function, default None
3068+
If not None, apply the key function to every index element before
3069+
sorting. Identical to key argument in built-in sorted function.
30483070
30493071
Returns
30503072
-------
@@ -3127,7 +3149,20 @@ def sort_index(
31273149
baz two 5
31283150
bar two 7
31293151
dtype: int64
3152+
3153+
>>> s = Series([1, 2, 3, 4, 5, 6, 7, 8])
3154+
>>> s.sort_index(key=lambda x : -x)
3155+
7 8
3156+
6 7
3157+
5 6
3158+
4 5
3159+
3 4
3160+
2 3
3161+
1 2
3162+
0 1
3163+
dtype: int64
31303164
"""
3165+
31313166
# TODO: this can be combined with DataFrame.sort_index impl as
31323167
# almost identical
31333168
inplace = validate_bool_kwarg(inplace, "inplace")
@@ -3147,10 +3182,9 @@ def sort_index(
31473182
from pandas.core.sorting import lexsort_indexer
31483183

31493184
labels = index._sort_levels_monotonic()
3150-
codes = labels._get_codes_for_sorting()
31513185

31523186
indexer = lexsort_indexer(
3153-
codes,
3187+
labels._get_codes_for_sorting(),
31543188
orders=ascending,
31553189
na_position=na_position,
31563190
)

0 commit comments

Comments
 (0)