ajs*_*jsp 2 python performance numpy rank pandas
我有一些非常大的列表,我正在使用(> 1M行),我试图找到一个快速(最快的?)方式,给定一个浮点数,浮点数与浮点数列表相比,找到它的百分比排名与列表范围相比.这是我的尝试,但它非常慢:
X =[0.595068426145485,
0.613726840488019,
1.1532608695652,
1.92952380952385,
4.44137931034496,
3.46432160804035,
2.20331487122673,
2.54736842105265,
3.57702702702689,
1.93202764976956,
1.34720184204056,
0.824997304105564,
0.765782842381996,
0.615110856990126,
0.622708022872803,
1.03211045820975,
0.997225012974318,
0.496352327702226,
0.67103858866700,
0.452224068868272,
0.441842124852685,
0.447584524952608,
0.4645525042246]
val = 1.5
arr = np.array(X) #X is actually a pandas column, hence the conversion
arr = np.insert(arr,1,val, axis=None) #insert the val into arr, to then be ranked
st = np.sort(arr)
RANK = float([i for i,k in enumerate(st) if k == val][0])+1 #Find position
PCNT_RANK = (1-(1-round(RANK/len(st),6)))*100 #Find percentage of value compared to range
print RANK, PCNT_RANK
>>> 17.0 70.8333
Run Code Online (Sandbox Code Playgroud)
对于百分比排名,我可以建立一个分布和样本,不太确定,任何建议欢迎...它将被大量使用,所以任何加速将是有利的.
谢谢.
对数组进行排序似乎相当慢.如果你不需要在最后对数组进行排序,那么numpy的布尔运算会更快.
arr = np.array(X)
bool_array = arr < val # Returns boolean array
RANK = float(np.sum(bool_array))
PCT_RANK = RANK/len(X)
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,使用列表理解并避免一起使用numpy.
RANK = float(sum([x<val for x in X]))
PCT_RANK = RANK/len(X)
Run Code Online (Sandbox Code Playgroud)
做一些时间,上面的numpy解决方案在我的系统上给出了6.66 us,而列表理解方法给出了3.74 us.