Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中列表列表的移动平均值_Python_Numpy_Average - Fatal编程技术网

python中列表列表的移动平均值

python中列表列表的移动平均值,python,numpy,average,Python,Numpy,Average,我有一个大数组,但结构类似于: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] 在不展平阵列的情况下,获取5个元素的滚动平均值的最佳、最有效的方法是什么。 i、 e 值1为(0+1+2+3+4)/5=2 值二为(1+2+3+4+5)/5=3 值三为(2+3+4+5+6)/5=4 感谢伪代码(尽管它看起来有点像Python): 不必每次都将五个数字相加,您可能会做得更好。注意:这个答案并不具体 如果

我有一个大数组,但结构类似于:

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
在不展平阵列的情况下,获取5个元素的滚动平均值的最佳、最有效的方法是什么。 i、 e

值1为(0+1+2+3+4)/5=2

值二为(1+2+3+4+5)/5=3

值三为(2+3+4+5+6)/5=4

感谢

伪代码(尽管它看起来有点像Python):


不必每次都将五个数字相加,您可能会做得更好。

注意:这个答案并不具体

如果列表列表可以展平,这将更简单

from itertools import tee

def moving_average(list_of_list, window_size):
    nums = (n for l in list_of_list for n in l)
    it1, it2 = tee(nums)
    window_sum = 0
    for _ in range(window_size):
        window_sum += next(it1)
    yield window_sum / window_size
    for n in it1:
        window_sum += n
        window_sum -= next(it2)
        yield window_sum / window_size
最好的方法可能是将数组的视图提交到
统一\u过滤器
。我不确定这是否会挫败您的“无法展平阵列”,但如果不以某种方式重塑阵列,所有这些方法都会比以下方法慢得多:

import numpy as np
import scipy.ndimage.filters as filt

arr=np.array([[0,1,2,3,4],
[5,6,7,8,9],
[10,11,12,13,14],
[15,16,17,18,19]])

avg =  filt.uniform_filter(arr.ravel(), size=5)[2:-2]

print avg
[ 2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17]

print arr.shape  #Original array is not changed.
(4, 5)
“最佳”解决方案取决于您不想首先展平阵列的原因。如果数据在内存中是连续的,则使用跨步技巧是计算滚动平均值的有效方法,而无需显式展平数组:

In [1]: a = np.arange(20).reshape((4, 5))

In [2]: a
Out[2]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [3]: from numpy.lib.stride_tricks import as_strided

In [4]: s = a.dtype.itemsize

In [5]: aa = as_strided(a, shape=(16,5), strides=(s, s))

In [6]: np.average(aa, axis=1)
Out[6]: 
array([  2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,
        13.,  14.,  15.,  16.,  17.])

似乎
%5
在某些地方很有用,但我不是Python大师。您不想展平数组有什么特别的原因吗?
In [1]: a = np.arange(20).reshape((4, 5))

In [2]: a
Out[2]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [3]: from numpy.lib.stride_tricks import as_strided

In [4]: s = a.dtype.itemsize

In [5]: aa = as_strided(a, shape=(16,5), strides=(s, s))

In [6]: np.average(aa, axis=1)
Out[6]: 
array([  2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,  12.,
        13.,  14.,  15.,  16.,  17.])