【问题标题】:How to calculate percentile of score along z axis of 3d array?如何计算沿 3d 数组 z 轴的分数百分位数?
【发布时间】:2018-02-06 19:36:52
【问题描述】:

我正在尝试使用 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]])

我可以使用嵌套循环来做到这一点,但我将其应用于大型数组,因此需要更优化的方法。我很难弄清楚如何实现这一点。

【问题讨论】:

    标签: python arrays numpy 3d scipy


    【解决方案1】:

    您可以通过重塑数组来避免嵌套循环。我认为为了完全避免循环,您必须编写一个自定义百分位函数。

    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]]
    

    【讨论】:

    • 这与我已经做过的类似。我想在不循环行和列的情况下做到这一点。
    • 更新后的答案减少了循环嵌套。因为您想使用不同的分数,并且必须将它们输入一个只接受一个数组和一个分数的函数,所以您可能无法避免单循环。
    猜你喜欢
    • 2021-11-29
    • 2021-02-26
    • 2020-10-07
    • 1970-01-01
    • 2013-08-31
    • 1970-01-01
    • 2017-05-15
    • 2011-12-29
    • 2013-06-20
    相关资源
    最近更新 更多