使用numpy通过平均相邻值缩小数组大小
我有一个很大的数组,里面有成千上万的值,都是用numpy这个工具做的。我想通过对相邻的值进行平均来减小这个数组的大小。
a = [2,3,4,8,9,10]
#average down to 2 values here
a = [3,9]
#it averaged 2,3,4 and 8,9,10 together
简单来说,我的数组里有n个元素,我想把它缩减到X个值,并且希望它能像上面那样进行平均。
请问有没有办法用numpy来实现这个功能?(我已经在用它做其他事情,所以希望继续使用它。)
4 个回答
0
在这个例子中,我假设 a
是一个需要求平均值的一维 numpy 数组。在我下面提供的方法中,我们首先找出这个数组 a
的长度的因子。然后,我们选择一个合适的因子作为步长,用来对数组进行平均。
下面是代码。
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]
0
试试这个:
n_averaged_elements = 3
averaged_array = []
a = np.array([ 2, 3, 4, 8, 9, 10])
for i in range(0, len(a), n_averaged_elements):
slice_from_index = i
slice_to_index = slice_from_index + n_averaged_elements
averaged_array.append(np.mean(a[slice_from_index:slice_to_index]))
>>>> averaged_array
>>>> [3.0, 9.0]
0
看起来这对我来说是一个简单的不重叠的移动平均窗口,你觉得怎么样:
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.])
20
使用 reshape
和 mean
,你可以对一个大小为 N*m
的一维数组中的每 m
个相邻值进行平均计算,其中 N
是任何正整数。举个例子:
import numpy as np
m = 3
a = np.array([2, 3, 4, 8, 9, 10])
b = a.reshape(-1, m).mean(axis=1)
#array([3., 9.])
1) a.reshape(-1, m)
这行代码会把数组变成一个二维的形式,但不会复制数据:
array([[ 2, 3, 4],
[ 8, 9, 10]])
2) 然后在第二个轴上(axis=1
)计算平均值,这样就能得到每一行的平均值,结果是:
array([3., 9.])