Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Pandas Index.sort_values()

Python | Pandas Index.sort_values()

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.




# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.Index(['Beagle', 'Pug', 'Labrador',
             'Sephard', 'Mastiff', 'Husky'])
  
# Print the index
idx


Output :

Now we will sort the index labels in the ascending order.




# Sorting the index labels
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.




# importing pandas as pd
import pandas as pd
  
# Creating the index 
idx = pd.Index([22, 14, 8, 56, 27, 21, 51, 23])
  
# Print the index
idx


Output :

Now we will sort the index labels in non-increasing order.




# sort the values in descending 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.

RELATED ARTICLES

Most Popular

Recent Comments