计算数据帧列中每个值的百分位数

Pra*_*nka 3 python performance scipy percentile pandas

我试图a从DataFrame 计算列中每个值的百分位数x.

有没有更好的方法来编写以下代码?

x["pcta"] = [stats.percentileofscore(x["a"].values, i) 
                                    for i in x["a"].values]
Run Code Online (Sandbox Code Playgroud)

我希望看到更好的表现.

Bra*_*mon 8

看起来你想要Series.rank():

x.loc[:, 'pcta'] = x.rank(pct=True) # will be in decimal form
Run Code Online (Sandbox Code Playgroud)

性能:

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
Run Code Online (Sandbox Code Playgroud)