2014-10-29 80 views
3

我在numpy中有數以千計的val數組。我想通過平均相鄰值來減小它的大小。 例如:用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(已經使用它的其他事情,所以我想堅持下去)。

+1

我打算提出'reshape'然後'mean',但是這與[這個問題]接受的答案是一樣的(http:// stackoverflow.com/questions/20322079/downsample-a-1d-numpy-array)。這會爲你的目的工作嗎? – DSM 2014-10-29 18:56:37

+0

@AdamHaile你試過下面的答案 – 2015-05-27 16:29:09

回答

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.]) 
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] 
5

正如在評論中提到,你想要的可能是:

group = 3 
a = a.reshape(-1, group).mean(axis=1) 
相關問題