Open In App

Python | Pandas Series.sort_index()

Last Updated : 05 Feb, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.

Pandas Series.sort_index() function is used to sort the index labels of the given series object.

Syntax: Series.sort_index(axis=0, level=None, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’, sort_remaining=True)

Parameter :
axis : Axis to direct sorting. This can only be 0 for Series.
level : If not None, sort on values in specified index level(s).
ascending : Sort ascending vs. descending.
inplace : If True, perform operation in-place.
kind : Choice of sorting algorithm.
na_position : Argument ‘first’ puts NaNs at the beginning, ‘last’ puts NaNs at the end.
sort_remaining : If true and sorting by level and index is multilevel, sort by other levels too (in order) after sorting by specified level.

Returns : Series

Example #1: Use Series.sort_index() function to sort the index labels of the given series object.




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
  
# Create the Index
index_ = ['City 5', 'City 6', 'City 4', 'City 2', 'City 3', 'City 1'
  
# set the index
sr.index = index_
  
# Print the series
print(sr)


Output :

Now we will use Series.sort_index() function to sort the index labels of the given series object.




# sort the index labels
sr.sort_index()


Output :

As we can see in the output, the Series.sort_index() function has successfully sorted the index labels of the given series object.
 
Example #2: Use Series.sort_index() function to sort the index labels of the given series object.




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
  
# Create the Index
index_ = [5, 3, 2, 1, 4]
  
# set the index
sr.index = index_
  
# Print the series
print(sr)


Output :

Now we will use Series.sort_index() function to sort the index labels of the given series object.




# sort the index labels
sr.sort_index()


Output :

As we can see in the output, the Series.sort_index() function has successfully sorted the index labels of the given series object.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads