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.
import pandas as pd
sr = pd.Series([ 'New York' , 'Chicago' , 'Toronto' , 'Lisbon' , 'Rio' , 'Moscow' ])
didx = pd.DatetimeIndex(start = '2014-08-01 10:00' , freq = 'W' ,
periods = 6 , tz = 'Europe/Berlin' )
sr.index = didx
print (sr)
|
Output :
Now we will use Series.sort_values()
function to sort the elements of the given series object in ascending order.
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.
import pandas as pd
sr = pd.Series([ 19.5 , 16.8 , 22.78 , 20.124 , 18.1002 ])
print (sr)
|
Output :
Now we will use Series.sort_values()
function to sort the elements of the given series object 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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...