4

我有一个不同大小的数组,我想从中平均每个连续的 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 会剪掉最后一个值。理想情况下,我会创建一个最后一个值,它是剩余值的平均值,同时保持代码紧凑。

这些都适用于我的目的,但我不确定它们是否对更大的数组最有效。

先感谢您!

4

2 回答 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]
于 2013-08-30T17:31:50.417 回答
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 ])
于 2013-08-30T18:28:48.490 回答