Python | Pandas Index.sort_values()
Last Updated :
18 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.sort_values()
function is used to sort the index values. The function return a sorted copy of the index. Apart from sorting the numerical values, the function can also sort string type values.
Syntax: Index.sort_values(return_indexer=False, ascending=True)
Parameters :
return_indexer : Should the indices that would sort the index be returned.
ascending : Should the index values be sorted in an ascending order.
Returns : Sorted copy of the index.
sorted_index : pandas.Index
indexer : numpy.ndarray, optional
The indices that the index itself was sorted by.
Example #1: Use Index.sort_values()
function to sort the values present in the index.
import pandas as pd
idx = pd.Index([ 'Beagle' , 'Pug' , 'Labrador' ,
'Sephard' , 'Mastiff' , 'Husky' ])
idx
|
Output :
Now we will sort the index labels in the ascending order.
idx.sort_values(ascending = True )
|
Output :
As we can see in the output, the function has returned an index with its labels sorted.
Example #2: Use Index.sort_values()
function to sort the index labels in the descending order.
import pandas as pd
idx = pd.Index([ 22 , 14 , 8 , 56 , 27 , 21 , 51 , 23 ])
idx
|
Output :
Now we will sort the index labels in non-increasing order.
idx.sort_values(ascending = False )
|
Output :
As we can see in the output, the function has returned a new index with its labels sorted in decreasing order.
Share your thoughts in the comments
Please Login to comment...