Python | Pandas Series.sort_values()
Last Updated :
05 Feb, 2019
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_values()
function is used to sort the given series object in ascending or descending order by some criterion. The function also provides the flexibility of choosing the sorting algorithm.
Syntax: Series.sort_values(axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')
Parameter :
axis : Axis to direct sorting.
ascending : If True, sort values in ascending order, otherwise 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.
Returns : Series
Example #1: Use
Series.sort_values()
function to sort the elements of the given series object in lexicographical order.
Python3
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
# Create the Datetime Index
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',
periods = 6, tz = 'Europe/Berlin')
# set the index
sr.index = didx
# Print the series
print(sr)
Output :

Now we will use
Series.sort_values()
function to sort the elements of the given series object in ascending order.
Python3 1==
# sort the values in ascending order
sr.sort_values()
Output :

As we can see in the output, the
Series.sort_values()
function has successfully sorted the elements of the given series object in ascending order.
Example #2: Use
Series.sort_values()
function to sort the elements of the given series object in descending order.
Python3
# importing pandas as pd
import pandas as pd
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
# Print the series
print(sr)
Output :

Now we will use
Series.sort_values()
function to sort the elements of the given series object in descending order.
Python3 1==
# sort the values in descending order
sr.sort_values(ascending = False)
Output :

As we can see in the output, the
Series.sort_values()
function has successfully sorted the elements of the given series object in descending order.