Python | Pandas Series.rank()
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.rank() function compute numerical data ranks (1 through n) along axis. Equal values are assigned a rank that is the average of the ranks of those values.
Syntax: Series.rank(axis=0, method=’average’, numeric_only=None, na_option=’keep’, ascending=True, pct=False)
Parameter :
axis : index to direct ranking
method : {‘average’, ‘min’, ‘max’, ‘first’, ‘dense’}
numeric_only : Include only float, int, boolean data. Valid only for DataFrame or Panel objects
na_option : {‘keep’, ‘top’, ‘bottom’}
ascending : False for ranks by high (1) to low (N)
pct : Computes percentage rank of dataReturns : ranks : same type as caller
Example #1: Use Series.rank() function to rank the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the indexsr.index = index_ # Print the seriesprint(sr) |
Output :

Now we will use Series.rank() function to return the rank of the underlying data of the given Series object.
# assign rankresult = sr.rank() # Print the resultprint(result) |
Output :

As we can see in the output, the Series.rank() function has assigned rank to each element of the given Series object.
Example #2: Use Series.rank() function to rank the underlying data of the given Series object. The given data also contains some equal values.
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6, 25]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp', 'Appy'] # set the indexsr.index = index_ # Print the seriesprint(sr) |
Output :

Now we will use Series.rank() function to return the rank of the underlying data of the given Series object.
# assign rankresult = sr.rank() # Print the resultprint(result) |
Output :

As we can see in the output, the Series.rank() function has assigned rank to each element of the given Series object. Notice equal values has been assigned a rank which is the average of their ranks.




