Skip to content

Commit a0b07ad

Browse files
DOC: updated inline documentation for key sorting
1 parent 257c127 commit a0b07ad

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
@@ -4817,9 +4817,8 @@ def sort_index(
48174817
elif isinstance(labels, ABCMultiIndex):
48184818
from pandas.core.sorting import lexsort_indexer
48194819

4820-
codes = labels._get_codes_for_sorting()
48214820
indexer = lexsort_indexer(
4822-
codes,
4821+
labels._get_codes_for_sorting(),
48234822
orders=ascending,
48244823
na_position=na_position,
48254824
)

pandas/core/series.py

+36-2
Original file line numberDiff line numberDiff line change
@@ -2913,6 +2913,9 @@ def sort_values(
29132913
na_position : {'first' or 'last'}, default 'last'
29142914
Argument 'first' puts NaNs at the beginning, 'last' puts NaNs at
29152915
the end.
2916+
key : function, default None
2917+
If not None, apply the key function to every value before
2918+
sorting. Identical to key argument in built-in sorted function.
29162919
29172920
Returns
29182921
-------
@@ -2995,6 +2998,22 @@ def sort_values(
29952998
2 d
29962999
0 z
29973000
dtype: object
3001+
3002+
>>> s = pd.Series(['a', 'B', 'c', 'D', 'e'])
3003+
>>> s.sort_values()
3004+
1 B
3005+
3 D
3006+
0 a
3007+
2 c
3008+
4 e
3009+
dtype: object
3010+
>>> s.sort_values(key=str.lower)
3011+
0 a
3012+
1 B
3013+
2 c
3014+
3 D
3015+
4 e
3016+
dtype: object
29983017
"""
29993018
inplace = validate_bool_kwarg(inplace, "inplace")
30003019
# Validate the axis parameter
@@ -3100,6 +3119,9 @@ def sort_index(
31003119
sort_remaining : bool, default True
31013120
If True and sorting by level and index is multilevel, sort by other
31023121
levels too (in order) after sorting by specified level.
3122+
key : function, default None
3123+
If not None, apply the key function to every index element before
3124+
sorting. Identical to key argument in built-in sorted function.
31033125
31043126
Returns
31053127
-------
@@ -3182,7 +3204,20 @@ def sort_index(
31823204
baz two 5
31833205
bar two 7
31843206
dtype: int64
3207+
3208+
>>> s = Series([1, 2, 3, 4, 5, 6, 7, 8])
3209+
>>> s.sort_index(key=lambda x : -x)
3210+
7 8
3211+
6 7
3212+
5 6
3213+
4 5
3214+
3 4
3215+
2 3
3216+
1 2
3217+
0 1
3218+
dtype: int64
31853219
"""
3220+
31863221
# TODO: this can be combined with DataFrame.sort_index impl as
31873222
# almost identical
31883223
inplace = validate_bool_kwarg(inplace, "inplace")
@@ -3202,10 +3237,9 @@ def sort_index(
32023237
from pandas.core.sorting import lexsort_indexer
32033238

32043239
labels = index._sort_levels_monotonic()
3205-
codes = labels._get_codes_for_sorting()
32063240

32073241
indexer = lexsort_indexer(
3208-
codes,
3242+
labels._get_codes_for_sorting(),
32093243
orders=ascending,
32103244
na_position=na_position,
32113245
)

0 commit comments

Comments
 (0)