In [3]:
import numpy as np
a = np.array([2,3,4,8,9,10])
window_sz = 3
a[:len(a)/window_sz*window_sz].reshape(-1,window_sz).mean(1)
#you want to be sure your array can be reshaped properly, so the [:len(a)/window_sz*window_sz] part
Out[3]:
array([ 3., 9.])
import numpy as np
from functools import reduce
''' Function to find factors of a given number 'n' '''
def factors(n):
return list(set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
a = [2,3,4,8,9,10] #Given array.
'''fac: list of factors of length of a.
In this example, len(a) = 6. So, fac = [1, 2, 3, 6] '''
fac = factors(len(a))
'''step: choose an appropriate step size from the list 'fac'.
In this example, we choose one of the middle numbers in fac
(3). '''
step = fac[int( len(fac)/3 )+1]
'''avg: initialize an empty array. '''
avg = np.array([])
for i in range(0, len(a), step):
avg = np.append( avg, np.mean(a[i:i+step]) ) #append averaged values to `avg`
print avg #Prints the final result
[3.0, 9.0]
4条答案
按热度按时间im9ewurl1#
使用
reshape
和mean
,可以对大小为N*m
的一维数组的每个m
相邻值求平均值,其中N
为任意正整数。例如:1)
a.reshape(-1, m)
将在不复制数据的情况下创建阵列的2D图像:2)取第二个轴(
axis=1
)的平均值,然后计算每行的平均值,得到:zujrkrfu2#
试试这个:
eoxn13cs3#
看起来像是一个简单的非重叠移动窗口平均值,那么:
pjngdqdw4#
在这个例子中,我假设
a
是需要求平均值的一维numpy数组,在下面给出的方法中,我们首先找到这个数组a
的长度因子,然后选择一个合适的因子作为求平均值的步长。下面是代码。