通过对数组中的n个连续数求平均值来构建数组

问题描述 投票:4回答:2

我有一个大小可变的数组,我希望根据该数组取平均每个连续的n个数字,然后构建另一个数组。

我提出了两种不同的方法,但是每种方法都有其各自的问题,我不确定这是否是解决此问题的最佳方法:

  1. 使用numpy.array_split()函数:

    import numpy as np
    no_splits = 3 #Or any number user defines
    no_items = int(np.random.random(1)*100) # To get a variable number of items
    pre_array = np.random.random(no_items)
    mean_array = np.mean(np.array_split(pre_array,no_splits)) 
    #This is efficient but gives an error if len(pre_array)%no_splits != 0
    
  2. enumerate(pre_array)替代项:

    mean_array = [np.mean(pre_array[i-no_splits+1:i]) for i, x in enumerate(pre_array) if i%no_splits == 0 and i != 0] 
    

这很好,但是如果i%no_splits!= 0,则剪切最后的值。理想情况下,我将创建一个剩余值的平均值的最后一个值,同时保持代码紧凑。

每种方法都可以达到我的目的,但是我不确定它们对于大型阵列是否最有效。

谢谢您!

python arrays numpy
2个回答
4
投票

使用uniform_filter

>>> import scipy.ndimage.filters as filter

>>> a=np.arange(5,dtype=np.double)
>>> filter.uniform_filter(a,size=3)
array([ 0.33333333,  1.        ,  2.        ,  3.        ,  3.66666667])

#What this is actually doing
>>> np.mean([0,0,1]) #ind0
0.33333333333333331
>>> np.mean([0,1,2]) #ind1
1.0
>>> np.mean([1,2,3]) #ind2
2.0

可以与任何大小的窗口一起使用。

>>> filter.uniform_filter(a,size=5)
array([ 0.8,  1.2,  2. ,  2.8,  3.2])

这里的警告是,累加器将是数组的dtype。


以三为一组,然后取平均值:

def stride_mean(arr,stride):
    extra = arr.shape[0]%stride
    if extra==0:
        return np.mean(arr.reshape(-1,stride),axis=1)
    else:
        toslice = arr.shape[0]-extra
        first = np.mean(arr[:toslice].reshape(-1,stride),axis=1)
        rest = np.mean(arr[toslice:])
        return np.hstack((first,rest))

print pre_array
[ 0.50712539  0.75062019  0.78681352  0.35659332]

print stride_mean(pre_array,3)
[ 0.6815197   0.35659332]

1
投票
no_splits = 3
no_items = 100
a = np.random.rand(no_items)

no_bins = no_splits + no_items % no_splits
b = np.empty((no_bins,), dtype=a.dtype)
endpoint = no_items//no_splits

b[:no_splits] = np.mean(a[:endpoint*no_splits].reshape(-1, endpoint),
                       axis=-1)
b[no_splits:] = np.mean(a[endpoint*no_splits:])
>>> b
array([ 0.49898723,  0.49457975,  0.45601632,  0.5316093 ])
© www.soinside.com 2019 - 2024. All rights reserved.