Spearmans Rank Correlation

Preliminaries

Create Data

Calculate Spearman’s Rank Correlation

Spearman’s rank correlation is the Pearson’s correlation coefficient of the ranked version of the variables.

# Create a function that takes in x's and y'sdefspearmans_rank_correlation(xs,ys):# Calculate the rank of x'sxranks=pd.Series(xs).rank()# Caclulate the ranking of the y'syranks=pd.Series(ys).rank()# Calculate Pearson's correlation coefficient on the ranked versions of the datareturnscipy.stats.pearsonr(xranks,yranks)

# Run the functionspearmans_rank_correlation(x,y)[0]

0.90377360145618091

Calculate Spearman’s Correlation Using SciPy

# Just to check our results, here it Spearman's using Scipyscipy.stats.spearmanr(x,y)[0]