jll
jll

Reputation: 815

fast way to compute vectorized percentiles in numpy/scipy?

given an array of values:

v = np.random.randn(100)

what's the fastest way to compute the percentile of each element in the array? the following is slow:

%timeit map(lambda e: scipy.stats.percentileofscore(v, e), v)
100 loops, best of 3: 5.1 ms per loop

Upvotes: 2

Views: 1655

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114841

You could use scipy.stats.rankdata() to achieve the same result:

In [58]: v = np.random.randn(10)

In [59]: print(list(map(lambda e: scipy.stats.percentileofscore(v, e), v)))
[30.0, 40.0, 50.0, 90.0, 20.0, 60.0, 10.0, 70.0, 80.0, 100.0]

In [60]: from scipy.stats import rankdata

In [61]: rankdata(v)*100/len(v)
Out[61]: array([  30.,   40.,   50.,   90.,   20.,   60.,   10.,   70.,   80.,  100.])

Upvotes: 4

Related Questions