I am trying to calculate percentile for every value in column a
from a DataFrame x
.
Is there a better way to write the following piece of code?
x["pcta"] = [stats.percentileofscore(x["a"].values, i)
for i in x["a"].values]
I would like to see better performance.
It seems like you want Series.rank()
:
x.loc[:, 'pcta'] = x.rank(pct=True) # will be in decimal form
Performance:
import scipy.stats as scs
%timeit [scs.percentileofscore(x["a"].values, i) for i in x["a"].values]
1000 loops, best of 3: 877 µs per loop
%timeit x.rank(pct=True)
10000 loops, best of 3: 107 µs per loop
来源:https://stackoverflow.com/questions/44211653/calculate-percentile-for-every-value-in-a-column-of-dataframe