我正在尝试使用 scipy.stats.percentileofscore() 沿 3d numpy 数组的 z 轴计算百分位数,得分在 2d 数组中。
例如,我的 3d 数组可能如下所示:
data = array([[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]],
[[ 2., 2., 2.],
[ 2., 2., 2.],
[ 2., 2., 2.]],
[[ 3., 3., 3.],
[ 3., 3., 3.],
[ 3., 3., 3.]]])
计算百分位数的分数可能如下所示:
scores = array([[ 1., 1., 2.],
[ 1., 1., 2.],
[ 1., 1., 2.]])
我想以这种方式在每个位置 (m,n) 应用 percentileofscore():
percentileofscore(data[:,m,n], scores[m,n])
结果是这样的:
array([[ 33.33, 33.33, 66.66],
[ 33.33, 33.33, 66.66],
[ 33.33, 33.33, 66.66]])
我可以使用嵌套循环执行此操作,但我将其应用于大型数组,因此需要更优化的方法。我很难思考如何实现这一目标。
请您参考如下方法:
您可以通过 reshape 数组来避免嵌套循环。我认为,为了完全避免循环,您必须编写自定义百分位数函数。
import numpy as np
from scipy.stats import percentileofscore
x = 3
y = 3
z = 3
d = a.reshape(z, x*y)
scores_d = scores.reshape(x*y,1)
percentiles_d = [percentileofscore(d[:, i], scores_d[i]) for i in range(x*y)]
percentiles_d = np.round(np.array(percentiles_d), 2).reshape(x,y)
print(percentiles_d)
[[ 33.33 33.33 66.67]
[ 33.33 33.33 66.67]
[ 33.33 33.33 66.67]]
