【问题标题】:array of neighbor averages邻居平均值数组
【发布时间】:2012-06-01 11:03:22
【问题描述】:

什么函数func 计算n-1 大小的数组,该数组是大小为n 的数组的后续元素的平均值(即窗口宽度为2 的移动平均值)?

func(numpy.array([1,2,3,4,5]))
# return numpy.array([1.5, 2.5, 3.5, 4.5])

【问题讨论】:

    标签: numpy average


    【解决方案1】:

    这里不需要函数:

    import numpy as np
    
    x = np.array([1,2,3,4,5])
    x_f2 = 0.5*(x[1:] + x[:-1])
    

    如果你想要它作为一个函数:

    def window(x, n):
        return (x[(n-1):] + x[:-(n-1)])/float(n)
    

    【讨论】:

      【解决方案2】:
      >>> x = np.array([1,2,3,4,5])
      >>> np.vstack([x[1:], x[:-1]]).mean(axis=0)
      

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 1970-01-01
        • 2014-10-31
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 2011-06-17
        • 2011-11-12
        • 1970-01-01
        相关资源
        最近更新 更多