【问题标题】:Multiple calculations of standard deviation on array subsets by index按索引对数组子集的标准差进行多次计算
【发布时间】:2018-07-12 18:55:15
【问题描述】:

假设我有一个 numpy 数组:my_array = np.random.rand(100)

和另一个索引数组:ind_array = ([35, 58, 77])

计算my_array 中每个ind_array 索引周围10 个值的标准差的最快方法是什么? (即np.std(my_array[30:40]), np.std(my_array[53:63]), np.std(my_array[72:82])

显然可以使用 for 循环,但我担心它会太慢。

谢谢

【问题讨论】:

    标签: python performance numpy vectorization


    【解决方案1】:

    方法#1:一种利用broadcasting的方法-

    np.std(my_array[ind_array[:,None] + np.r_[-5:5]],axis=1)
    

    方法 #2: 我们还可以利用基于 scikit-image's view_as_windowsnp.lib.stride_tricks.as_strided 来获得更有效的解决方案 -

    from skimage.util.shape import view_as_windows
    
    np.std(view_as_windows(my_array,(10))[ind_array-5],axis=1)
    

    【讨论】:

    • 完美!谢谢。
    猜你喜欢
    • 2020-11-08
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多