通过使用numpy平均相邻值来减小数组大小

时间:2014-10-29 18:51:47

标签: python arrays numpy mean

我在numpy中有成千上万的val。我想通过平均相邻值来减小其大小。 例如:

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 :(得分:6)

正如评论中所提到的,你想要的可能是:

group = 3
a = a.reshape(-1, group).mean(axis=1)

答案 1 :(得分: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.])

答案 2 :(得分: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]

答案 3 :(得分: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]