I want to efficiently calculate Spearman correlations between a Numpy array and every Pandas DataFrame
row:
import pandas as pd
import numpy as np
from scipy.stats import spearmanr
n_rows = 2500
cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
df = pd.DataFrame(np.random.random(size=(n_rows, len(cols))), columns=cols)
v = np.random.random(size=len(cols))
corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
corr = pd.Series(corr)
For now, the calculation time of corr
is:
%timeit corr, _ = zip(*df.apply(lambda x: spearmanr(x,v), axis=1))
>> 1.26 s ± 5.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
I found another good approach but it calculates only Pearson correlations:
%timeit df.corrwith(pd.Series(v, index=df.columns), axis=1)
>> 466 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Is there a way to calculate Spearman correlations faster?