本文介绍了在数组切片上向量化numpy均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种向量化函数的方法,以便输出将是一个均值数组,其中每个均值代表输入数组0索引中值的均值?循环这非常简单,但是我正在努力提高效率.例如0 =平均值(0),1 =平均值(0-1),N =平均值(0-N)

Is there a way to vectorize a function so that the output would be an array of means where each mean represents the mean of the values from 0-index of the input array? Looping this is pretty straightforward but I am trying to be as efficient as possible. e.g. 0 = mean(0), 1 = mean(0-1), N = mean(0-N)

推荐答案

预期的操作可以 coined 作为cumulative averaging.因此,一个明显的解决方案将涉及cumulative summation并将这些求和除以参与每个此类求和的元素数.因此,矢量化的实现将涉及 np.cumsum ,然后除以 np.arange 并概括为ndarray,就像这样-

The intended operation could be coined as cumulative averaging. So, an obvious solution would involve cumulative summation and dividing those summations by the number of elements participating for each such summation. Thus, a vectorized implementation would involve np.cumsum and then dividing by the number of participating elements that could be obtained with np.arange and generalized for an ndarray, like so -

def cummean(A,axis):
    """ Cumulative averaging

    Parameters
    ----------    
    A    : input ndarray
    axis : axis along which operation is to be performed

    Output
    ------    
    Output : Cumulative averages along the specified axis of input ndarray
    """

    return np.true_divide(A.cumsum(axis),np.arange(1,A.shape[axis]+1))

这篇关于在数组切片上向量化numpy均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:10