@@ -1781,6 +1781,31 @@ used to sort a pandas object by its index levels.
1781
1781
# Series
1782
1782
unsorted_df[' three' ].sort_index()
1783
1783
1784
+ .. _basics.sort_index_key :
1785
+
1786
+ .. versionadded :: 1.1.0
1787
+
1788
+ Sorting by index also supports a ``key `` parameter that takes a callable
1789
+ function to apply to the index being sorted. For `MultiIndex ` objects,
1790
+ the key is applied per-level to the levels specified by `level `.
1791
+
1792
+ .. ipython :: python
1793
+
1794
+ s1 = pd.DataFrame({
1795
+ " a" : [' B' , ' a' , ' C' ],
1796
+ " b" : [1 , 2 , 3 ],
1797
+ " c" : [2 , 3 , 4 ]
1798
+ }).set_index(list (" ab" ))
1799
+ s1
1800
+
1801
+ .. ipython :: python
1802
+
1803
+ s1.sort_index(level = " a" )
1804
+ s1.sort_index(level = " a" , key = lambda idx : idx.str.lower())
1805
+
1806
+ For information on key sorting by value, see :ref: `value sorting
1807
+ <basics.sort_value_key>`.
1808
+
1784
1809
.. _basics.sort_values :
1785
1810
1786
1811
By values
@@ -1813,6 +1838,39 @@ argument:
1813
1838
s.sort_values()
1814
1839
s.sort_values(na_position = ' first' )
1815
1840
1841
+ .. _basics.sort_value_key :
1842
+
1843
+ .. versionadded :: 1.1.0
1844
+
1845
+ Sorting also supports a ``key `` parameter that takes a callable function
1846
+ to apply to the values being sorted.
1847
+
1848
+ .. ipython :: python
1849
+
1850
+ s1 = pd.Series([' B' , ' a' , ' C' ])
1851
+
1852
+ .. ipython :: python
1853
+
1854
+ s1.sort_values()
1855
+ s1.sort_values(key = lambda x : x.str.lower())
1856
+
1857
+ `key ` will be given the :class: `Series ` of values and should return a ``Series ``
1858
+ or array of the same shape with the transformed values. For `DataFrame ` objects,
1859
+ the key is applied per column, so the key should still expect a Series and return
1860
+ a Series, e.g.
1861
+
1862
+ .. ipython :: python
1863
+
1864
+ df = pd.DataFrame({" a" : [' B' , ' a' , ' C' ], " b" : [1 , 2 , 3 ]})
1865
+
1866
+ .. ipython :: python
1867
+
1868
+ df.sort_values(by = ' a' )
1869
+ df.sort_values(by = ' a' , key = lambda col : col.str.lower())
1870
+
1871
+ The name or type of each column can be used to apply different functions to
1872
+ different columns.
1873
+
1816
1874
.. _basics.sort_indexes_and_values :
1817
1875
1818
1876
By indexes and values
0 commit comments